从JSON文件Java获取字符串
我想使用“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) {
`
# 1 楼答案
听起来像
在Json文件中是意外的
# 2 楼答案
首先,您提供的JSON是一个JSONObject而不是数组。要解析它,以下代码块将起作用
输出将是:{“Tenorhorn”:“2”,“Tuba”:“2”,“Posune”:“3”,“Schreibweise”:“B”,“SonstigeInst”:“Author”:“tesaf”,“Trompete”:“2”,“Wertung”:“1”,“Partitur”:“Partitur”,“Path”:“}
为了回答关于数组的问题,可以使用Json数组而不是单个Json对象
例如:
}]
您的代码将是
还有一件事需要记住的是IOException | ParseException e1-如果使用低于1.7的JDK,则不允许使用多捕获参数