我想使用“JSON SIMPLE”API读取JSON文件。
JSONParser parser = new JSONParser();
JSONArray a = null;
try {
a = (JSONArray) parser.parse(new FileReader("C:\\data\\data.json"));
} catch (IOException | ParseException e1) {
e1.printStackTrace();
}
for (Object o : a) {
JSONObject jsonObject = (JSONObject) o;
String name = (String) jsonObject.get("Test");
System.out.println(name);
}
我的JSON文件:
{
"Test" : {
"Tenorhorn" : "2",
"Tuba" : "2",
"Posaune" : "3",
"Schreibweise" : "B",
"SonstigeInst" : "",
"Author" : "tesaf",
"Wertung" : "1",
"Trompete" : "2",
"Partitur" : "Partitur",
"Path" : ""
}
}
但我得到以下例外:
"Unexpected token LEFT BRACE({) at position 237."
At position 237 is: ` } catch (IOException | ParseException e1) {
`
答案 0 :(得分:0)
ObservableCollection
听起来像
"Unexpected token LEFT BRACE({) at position 237."
At position 237 is: ` } catch (IOException | ParseException e1) {
在Json文件中是意外的
答案 1 :(得分:0)
首先,您提供的JSON是JSONObject而不是数组。要解析它,以下代码块将起作用..
JSONParser parser = new JSONParser();
JSONObject a = null;
try {
FileReader fileReader = new FileReader("C:\\data\\data.json");
a = (JSONObject) parser.parse(fileReader);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println(a.get("Test"));
输出将是:{" Tenorhorn":" 2"," Tuba":" 2"," Posaune&# 34;:" 3"" Schreibweise":" B"" SonstigeInst":""&# 34;作者":" tesaf"" Trompete":" 2"" Wertung":" 1&#34 ;," Partitur":" Partitur""路径":""}
要回答关于数组的问题,可以使用Json数组而不是单个Json对象。
例如:
[{
"Tenorhorn": "2",
"Tuba": "2",
"Posaune": "3",
"Schreibweise": "B",
"SonstigeInst": "",
"Author": "tesaf",
"Wertung": "1",
"Trompete": "2",
"Partitur": "Partitur",
"Path": ""
}]
您的代码将是..
JSONArray a = null;
try {
FileReader fileReader = new FileReader("C:\\data\\data.json");
a = (JSONArray) parser.parse(fileReader);
} catch (Exception e1) {
e1.printStackTrace();
}
for (Object o : a) {
JSONObject jsonObject = (JSONObject) o;
System.out.println(jsonObject);
}
要记住的另一件事是IOException | ParseException e1 - 如果使用低于1.7的JDK
,则不允许使用多捕获参数