位置0处的意外字符(i)。 - 使用Java解析JSON [英] Unexpected character (i) at position 0. - JSON Parsing with Java
问题描述
{
"0" : {
"upc" : "00000000005",
"name" : "Weighable Soup Cups",
"location" : "5310ed21d5dc7aaa0343a932"
},
"1" : {
"upc" : "00000000011",
"name" : "OF Reuseable Bags",
"location" : "5310ed21d5dc7aaa0343a932"
}
}
这是我试图解析的JSON的片段。这是我正在使用的代码:
Thats a snippet of the JSON I am trying to parse. Here is the code I am using:
public class Main {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
jsonObject = (JSONObject) parser.parse("items.json");
} catch (ParseException e) {
e.printStackTrace();
}
JSONObject structure = (JSONObject) jsonObject.get("0");
System.out.println(structure.get("upc"));
}
}
由于某种原因,在位置0错误时抛出意外字符(i)。据我所知,JSON文件格式正确用于解析,代码是可靠的,所以我不明白为什么这不起作用。谢谢。
For some reason throws an unexpected character (i) at position 0 error. As far as I know of the JSON file is formatted correctly for parsing and the code is solid, so I don't understand why this will not work. Thanks.
推荐答案
JSONParser #parse(String)
需要一个JSON字符串,而不是文件名。
JSONParser#parse(String)
expects a JSON string, not a file name.
您可以使用需要 Reader
的重载方法并提供 InputStreamReader
包装 FileInputStream
。
You can use the overloaded method that expects a Reader
and provide an InputStreamReader
which wraps a FileInputStream
.
jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("items.json")));
这篇关于位置0处的意外字符(i)。 - 使用Java解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!