位置 0 处出现意外字符 (i)。 - 使用 Java 进行 JSON 解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23144848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unexpected character (i) at position 0. - JSON Parsing with Java
提问by Nick Thoma
{
"0" : {
"upc" : "00000000005",
"name" : "Weighable Soup Cups",
"location" : "5310ed21d5dc7aaa0343a932"
},
"1" : {
"upc" : "00000000011",
"name" : "OF Reuseable Bags",
"location" : "5310ed21d5dc7aaa0343a932"
}
}
Thats a snippet of the JSON I am trying to parse. Here is the code I am using:
这是我试图解析的 JSON 片段。这是我正在使用的代码:
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"));
}
}
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.
出于某种原因,在位置 0 错误处抛出一个意外字符 (i)。据我所知,JSON 文件的格式正确用于解析并且代码是可靠的,所以我不明白为什么这不起作用。谢谢。
采纳答案by Sotirios Delimanolis
JSONParser#parse(String)
expects a JSON string, not a file name.
JSONParser#parse(String)
需要 JSON 字符串,而不是文件名。
You can use the overloaded method that expects a Reader
and provide an InputStreamReader
which wraps a FileInputStream
.
您可以使用需要 aReader
并提供InputStreamReader
包装 a的重载方法FileInputStream
。
jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("items.json")));