[英]json multiple json data parsing in java
I have a json input like this 我有一个像这样的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"
}]
I am using json simple jar to parse the json. 我正在使用json简单jar来解析json。 my code is: 我的代码是:
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());
}
Above code works fine, If i send single lock of data and without [ and ] bracket. 上面的代码工作正常,如果我发送数据的单锁并且没有[和]括号。 Above json is a valid json according to JSONLint json上方是根据JSONLint的有效json
Question: 题:
1) How do I parse above json having multiple data? 1)如何解析以上具有多个数据的json?
Something like below for your scenario, if you want to use json-simple: 如果您想使用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 https://code.google.com/p/json-simple/wiki/DecodingExamples
You'll see that to process your array instead of JSONObject you need to us JSONArray. 您会看到,要处理数组而不是JSONObject,您需要使用JSONArray。 The link has a full example. 该链接有完整的示例。
I typically use Jackson for my JSON parsing, it is pretty good. 我通常使用Jackson进行JSON解析,这非常好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.