I have a java application where I want to send json data fro servlet to a jsp. I am using mongodb as a database and Gson library for Json.
I am new to Java & Mongo.
Here is the code for querying the database:
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB database = mongoClient.getDB("MyTestDatabase");
coll = database.getCollection("players");
BasicDBObject fields = new BasicDBObject();
fields.put("_id", 0);
fields.put("Incident Date", 1);
fields.put("Longitude", 1);
fields.put("Latitude", 1);
fields.put("Address", 1);
fields.put("Status", 1);
fields.put("Name", 1);
doc.put("Address", "Mumbai");
cursor = coll.find(doc,fields);
And this is the result after querying the database
{ "_id" : { "$oid" : "5540cae37a104f6bbfe7c9f5"} , "Incident Date" : "30/4/2015" , "Longitude" : "77.61528809" , "Latitude" : "12.9245331" , "Address" : "Mumbai" , "Status" : "Ok" , "Name" : [ "1.ABC" , "2.XYZ" , "3.PQR"]}
What I want to achieve is to convert the above result into a JSON and access the JSON using fields such as 'Incident Date', 'Status' by parsing the result as json. I tried to parse the original result as json but I think it doesn't work like that
Here is what I have tried. 1. Converted the 'cursor' to ArrayList
List<DBObject> myList = new ArrayList<DBObject>();
myList = cursor.toArray();
Tried to convert the ArrayList into the JSON
JSON json =new JSON(); String serialize = json.serialize(cursor);
I tried the following code, but I am getting this error
JsonElement jelement = new JsonParser().parse(serialize);
System.out.println(jelement);
JsonObject jobject = jelement.getAsJsonObject();//error at this line
System.out.println(jobject);
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Object: [{"_id":{"$oid":"5540cae37a104f6bbfe7c9f5"},"Incident Date":"30/4/2015","Longitude":"77.61528809","Latitude":"12.9245331","Address":"Mumbai","Status":"Ok","Culprits Name":["1.ABC","2.XYZ","3.PQR"]}]
at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:90)
Can anyone please help me?