gpt4 book ai didi

java - 如何从文件中解析 JSON 数组?

转载 作者:行者123 更新时间:2023-12-01 16:51:16 28 4
gpt4 key购买 nike

我有来自文件的 JSON。

{  
"from_excel":[
{
"solution":"Fisrt",
"num":"1"
},
{
"solution":"Second",
"num":"2"
},
{
"solution":"third",
"num":"3"
},
{
"solution":"fourth",
"num":"4"
},
{
"solution":"fifth",
"num":"5"
}
]
}

并且想要解析解决方案和 Num 的列表。

使用liborg.json.simple.*

试试这个

        Object obj = parser.parse(new FileReader("E:\\json.txt"));        JSONObject jsonObject = (JSONObject) obj;        out.println(jsonObject.get("from_excel"));        JSONObject obj_new = (JSONObject) jsonObject.get("from_excel");        JSONArray solution = (JSONArray) obj_new.get("solution");        Iterator iterator = solution.iterator();        while (iterator.hasNext()) {            out.println(iterator.next());        }

我做错了什么?

如果尝试写

JSONObject solutions = (JSONArray) jsonObject.get("from_excel");

enter image description here

如果尝试写

JSONArray array = obj.getJSONArray("from_excel");

出现错误 enter image description here

最佳答案

工作解决方案

JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {

jsonObject = (JSONObject) parser.parse(new FileReader("E:\\json.txt"));

out.println("<br>"+jsonObject);


JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
// for row output 1
for(Object o: from_excel){
out.println("<br>"+o);
}
// for row output 2
Iterator iterator = from_excel.iterator();
while (iterator.hasNext()) {
out.println("<br>"+iterator.next());
}
// for item output 3
for (int i = 0; i < from_excel.size(); i++) {

JSONObject jsonObjectRow = (JSONObject) from_excel.get(i);
String num = (String) jsonObjectRow.get("num");
String solution = (String) jsonObjectRow.get("solution");
out.println("<br>num="+num+"; solution="+solution);
}
} catch (Exception e) {
out.println("Error: "+e);
}

关于java - 如何从文件中解析 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39689507/

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