[英]json multiple json data parsing in java
我有一個像這樣的json輸入
[ {
"Company":"BEG",
"Account":"1001",
"Deptid":"",
"Location":"",
"Transaction Date":"2014-07-15",
"Description":"Invoice",
"Debit":0.0,
"Credit":13.46,
"Invoice Nbr":"1682"
},
{
"Company":"BEG2",
"Account":"1002",
"Deptid":"23",
"Location":"NY",
"Transaction Date":"2014-07-15",
"Description":"Invoice",
"Debit":0.0,
"Credit":13.45,
"Invoice Nbr":"1682432"
},
....
....
},
{
"Company":"BEG99",
"Account":"1099",
"Deptid":"",
"Location":"",
"Transaction Date":"2014-07-15",
"Description":"Invoice",
"Debit":0.0,
"Credit":13.46,
"Invoice Nbr":"168243299"
}]
我正在使用json簡單jar來解析json。 我的代碼是:
public String appendData(String str) throws IOException, ParseException{
System.out.println("========Inside appendData======"+str);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(new StringReader(str));
double debit = (double) Double.parseDouble(jsonObject.get("Debit").toString());
}
上面的代碼工作正常,如果我發送數據的單鎖並且沒有[和]括號。 json上方是根據JSONLint的有效json
題:
1)如何解析以上具有多個數據的json?
如果您想使用json-simple,則類似於以下情況:
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(new StringReader(str));
if (obj instanceof JSONObject) {
JSONObject jo = (JSONObject) obj;
System.out.println(jo.get("Debit").toString());
} else {
JSONArray ja = (JSONArray) obj;
for(int i=0;i<ja.size();i++){
JSONObject jsonObject = (JSONObject)ja.get(i);
System.out.println(jsonObject.get("Debit").toString());
}
}
GSON庫對於此類任務非常簡單
https://code.google.com/p/json-simple/wiki/DecodingExamples
您會看到,要處理數組而不是JSONObject,您需要使用JSONArray。 該鏈接有完整的示例。
我通常使用Jackson進行JSON解析,這非常好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.