I want to extract the fields "2008" and "2009" in the field "total" from this json data. I tried but it shows null pointer exception..i don't know what went wrong. Below is the code which I had tried.
/*insertion of data*/
DB preDB = mongo.getDB("database");
DBCollection coll = preDB.getCollection("agrinindstry");
BasicDBObject doc1 = new BasicDBObject();
doc1.put("test", str);
coll.insert(doc1);
System.out.println(doc1);
/***retrieving data***/
DBCursor cursor = coll.find();
JSONArray mylist = new JSONArray();
String result = "";
while (cursor.hasNext())
{
result = cursor.next().get("2008").toString();
mylist.add(result);
System.out.println(mylist);
}
this is my json data
{"maindata":[
{
"title":"industry",
"2008":37,
"2009":44,
"2010":42
},
{
"title":"agriculture",
"2008":4,
"2009":0,
"2010":6
}
],
"total":{
"title:"sum",
"2008":41,
"2009":44,
"2010":48
}
}
((DBObject)cursor.next().get("total")).get("2008").toString();
Your task you can simplify by using any JAVA tootkit for JSON, take look into this example :
For more understanding on JSON and how to parse it, check this:
If you read the javadoc of JSONObject#get(String) which is actually HashMap.get(String), it states
Returns: the value to which the specified key is mapped, or null if this map contains no mapping for the key
Your JSON does not contain a mapping for the key time.
Edit:
Consider this to parse your JSON data:
{"schedule":{"service":{"type":"radio","key":"radio1","title":"BBC Radio 1",...
You need to first get schedule as a JSONObject, then service as a JSONObject, and then title as a normal String value. Apply this differently depending on the type of JSON value.
Try this:
//get the data from mongoDB which documents has "total" key.
DBObject dbObject = new BasicDBObject().append("total", new BasicDBObject("$exists", true));
DBCursor cursor = collection.find(dbObject);
JSONArray mylist = new JSONArray();
String result = "";
while (cursor.hasNext())
{
result = ((DBObject)cursor.next().get("total")).get("2008").toString();
mylist.add(result);
System.out.println(mylist);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.