Unexpected character (i) at position 0. - JSON Parsing with Java

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

{     "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:

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.

回答1:

JSONParser#parse(String) expects a JSON string, not a file name.

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"))); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!