2014-09-11 42 views
0

我想從這個json數據中提取字段「total」中的字段「2008」和「2009」。我試過,但它顯示空指針異常..我不知道出了什麼問題。下面是我嘗試過的代碼。從json數據中提取特定字段

/*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); 

      } 

這是我的JSON數據

{"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 

} 
} 

回答

0
((DBObject)cursor.next().get("total")).get("2008").toString(); 
+0

感謝ü@ waitingmyself..but它顯示例外異常在線程 「主」 了java.lang.RuntimeException:沒有更多的 – chopss 2014-09-11 05:31:38

+0

我覺得你的代碼只是一個提示我看不到你如何在代碼中插入數據。 'doc1.put(「test」,str);'什麼是str – waitingmyself 2014-09-11 06:04:52

0

你的任務,你可以通過使用JSON任何JAVA tootkit簡化,拿一下這個example

Check it out...

有關JSON的更多理解以及如何解析它,請檢查:

如果你讀的JSONObject#GET(字符串),這實際上是HashMap.get(字符串)的javadoc的,它指出

返回:指定鍵所映射的值,或爲null如果此映射包含沒有映射關鍵字

您的JSON不包含關鍵時間的映射。

編輯:

認爲這解析您的JSON數據:

 {"schedule":{"service":{"type":"radio","key":"radio1","title":"BBC Radio 1",... 

您需要首先獲得時間表一個JSONObject,然後服務作爲一個JSONObject,然後標題作爲一個正常的字符串值。根據JSON值的類型應用此方式。

See this link

0

試試這個:

 //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); 

     }