gpt4 book ai didi

java - java中json多个json数据解析

转载 作者:行者123 更新时间:2023-12-01 22:46:10 25 4
gpt4 key购买 nike

我有一个像这样的 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 simple 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());
}
}

关于java - java中json多个json数据解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25332791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com