gpt4 book ai didi

java - 如何在单个文件java中读取包含多个内容的JSON

转载 作者:行者123 更新时间:2023-12-01 13:09:13 24 4
gpt4 key购买 nike

我使用 JSON 时遇到了一个问题。我有这样的 JSON 文件

{"Text":"Here is some text","Make":"Admin","Name":"Hello"}
{"Text":"Here is some text","Make":"John","Name":"Hello"}
{"Text":"Here is some text","Make":"Admin","Name":"Hello"}

我需要从该文件中读取所有文本。我尝试但抛出异常这是我要阅读的代码

JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(new FileReader("Project.json"));

JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("Text");
System.out.println(name);

}
catch (IOException e) {
e.printStackTrace();
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}

感谢帮助

最佳答案

这不是有效的 JSON,应该是这样的

[{"Text":"Here is some text","Make":"Admin","Name":"Hello"},
{"Text":"Here is some text","Make":"John","Name":"Hello"},
{"Text":"Here is some text","Make":"Admin","Name":"Hello"}]

obj = parser.parse(new FileReader("Project.json"));
JSONArray jsonArray = (JSONArray) obj;

for (JSONObject jsonObject : jsonArray)
{
String name = (String) jsonObject.get("Text");
System.out.println(name);
}

希望这能解决您的问题

关于java - 如何在单个文件java中读取包含多个内容的JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23027051/

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