【问题标题】:A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' errorJSONObject 文本必须在 1 [字符 2 第 1 行] 处以 '{' 开头,并带有 '{' 错误
【发布时间】:2014-02-27 07:39:00
【问题描述】:
String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";

JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("get");
Object level = getSth.get("2");

System.out.println(level);

我参考了许多解析 this link 的解决方案,但仍然遇到同样的错误。 任何人都可以给我一个简单的解决方案来解析它。

【问题讨论】:

  • 这是有效的 json,请参阅 jsonlint.com 也许是你的代码?
  • 这个给定的 json 是正确的..您尝试过的代码,也请记录 cat
  • 错误在你的代码中;看起来您正在尝试使用 JSONObject 解析不是对象的 JSON 值。作为替代方案,使用更好的 JSON 库,例如 Jackson。
  • 尝试打印str.charAt(0),看看第一个字符是什么。它可能是 [ 在这种情况下它是一个 json 数组。或者你可能有某种隐藏的字符。
  • @ns47731,他发布了一个指向他正在解析的 JSON 的链接,但没有 [.不过,str.charAt(0) 仍然是一个很好的调试步骤。

标签: java android json parsing


【解决方案1】:

您的问题是 String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4"; 不是 JSON
您要做的是打开一个到“http://www.json-generator.com/j/cglqaRcMSW?indent=4”的HTTP 连接并解析 JSON 响应

String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";
JSONObject jsonObject = new JSONObject(JSON); // <-- Problem here!

不会打开与网站的连接并检索内容。

【讨论】:

    【解决方案2】:

    我有同样的问题。我来自服务器的 Json 响应是 [, and, ]:

    [{"DATE_HIRED":852344800000,"FRNG_SUB_ACCT":0,"MOVING_EXP":0,"CURRENCY_CODE":"CAD  ","PIN":"          ","EST_REMUN":0,"HM_DIST_CO":1,"SICK_PAY":0,"STAND_AMT":0,"BSI_GROUP":"           ","LAST_DED_SEQ":36}]
    

    http://jsonlint.com/ 表示有效的 json。您可以复制并验证它。

    我已修复以下代码作为临时解决方案:

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
    String result ="";
    String output = null;
    while ((result = br.readLine()) != null) {
        output = result.replace("[", "").replace("]", "");
        JSONObject jsonObject = new JSONObject(output); 
        JSONArray jsonArray = new JSONArray(output); 
        .....   
    }
    

    【讨论】:

    • 或者你可以使用 JSONArray jsonArray = new JSONArray(output);
    【解决方案3】:

    虽然 json 以“[”开头并以“]”结尾,这意味着这是 Json 数组,但请改用 JSONArray:

    JSONArray jsonArray = new JSONArray(JSON);
    

    如果需要,您可以将其与 List Test Object 进行映射:

    ObjectMapper mapper = new ObjectMapper();
    List<TestExample> listTest = mapper.readValue(String.valueOf(jsonArray), List.class);
    

    【讨论】:

      【解决方案4】:

      我也有,开头有一个空的换行符。 解决了它:

      int i = result.indexOf("{");
      result = result.substring(i);
      JSONObject json = new JSONObject(result.trim()); 
      System.out.println(json.toString(4));  
      

      【讨论】:

      • 像魅力一样工作
      【解决方案5】:

      由于代码语句的错误顺序,我遇到了同样的问题。保持以下顺序以解决问题。所有 get 方法语句首先和后面的 httpClient 方法。

            HttpClient httpClient = new HttpClient();
      get = new GetMethod(instanceUrl+usersEndPointUri);
      get.setRequestHeader("Content-Type", "application/json");
      get.setRequestHeader("Accept", "application/json");
      
      httpClient.getParams().setParameter("http.protocol.single-cookie-header", true);
      httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
      httpClient.executeMethod(get);
      

      【讨论】:

        【解决方案6】:

        在我的情况下,json 文件编码是个问题

        我在 vb .net 中生成 JSON 文件,内容如下: My.Computer.FileSystem.WriteAllText("newComponent.json", json.Trim, False)

        我尝试了这篇文章中的所有建议,但没有任何帮助。

        最终在 Notepad++ 中发现创建的文件是 UTF-8-BOM

        不确定它是如何获取该编码的,但在我将编码切换为 UTF-8 后,它在没有其他更改的情况下解决了。

        希望这对某人有所帮助。

        【讨论】:

          【解决方案7】:

          我遇到了同样的错误并努力修复它,然后 Nagaraja JB 在上面的回答帮助我修复了它。就我而言:

          以前: JSONObject response_json = new JSONObject(response_data);

          改为: JSONArray response_json = new JSONArray(response_data);

          这解决了它。

          【讨论】:

            【解决方案8】:

            当我尝试将列表转换为 json 时,由于一个小错误,我遇到了类似的问题。 如果将 List 转换为 json,它将返回 JSONArray 而不是 JSONObject。

            【讨论】:

              【解决方案9】:

              在我的情况下,我的 arraylist 向我抛出了 JSONObject 的错误,但我为我的 String 对象数组找到了这个解决方案

              List<String> listStrings= new ArrayList<String>();
              String json = new Gson().toJson(listStrings);
              return json;
              

              具有棱角的魅力 Gson 2.8.5 版

              【讨论】:

                【解决方案10】:

                我使用的文件是通过 Powershell 以 UTF-8 格式保存的。我将其更改为 ANSI 并解决了问题。

                【讨论】:

                  【解决方案11】:

                  回复:

                   [
                          {
                            "idGear": "1",
                            "name": "Nosilec za kolesa",
                            "year": "2005",
                            "price": "777.0"
                          }, {
                            "idGear": "2",
                            "name": "Stresni nosilci",
                            "year": "1983",
                            "price": "40.0"
                          }
                        ]
                  

                  假设您的回复与此回复有些相似。您可以使用 JSONArray 而不是 JSONObject,然后根据您的响应,您可以对其进行迭代或获取第 0 个索引处的元素。

                  JSONArray json_arr = new JSONArray(response_string);
                  JSONObject single_response = json_arr.get(0); //for single element
                  for(int i=0;i<json_arr.length();i++){         // OR iterate
                      JSONObject tmp = json_arr.get(i);
                  } 
                  

                  【讨论】:

                    【解决方案12】:

                    这个问题在 JSON 中不会发生。您需要使用 HttpURLConnection 打开 URL 连接。

                        HttpURLConnection connection = null;
                        try{            
                            URL url = new URL("http://www.json-generator.com/j/cglqaRcMSW?indent=4");
                            connection =  (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setRequestProperty("Content-Type","application/json");
                            connection.setRequestProperty("Accept","application/json");
                            connection.setUseCaches(false);
                            connection.setAllowUserInteraction(false);
                            connection.connect();
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                            StringBuffer stringBuffer = new StringBuffer();
                            String output;
                            while((output = bufferedReader.readLine()) != null ){
                                stringBuffer.append(output);
                            }
                            bufferedReader.close();
                            System.out.println(stringBuffer.toString());
                        }
                        catch(Exception e){
                            System.out.println(e);
                        }
                        finally{
                            if (connection != null) {
                            try {
                                connection.disconnect();
                            }catch (Exception ex) {
                                System.out.println("Error");
                            }
                         }
                    

                    【讨论】:

                      【解决方案13】:

                      您的 JSON 完全有效。尝试使用这些 JSON 类来解析它。 http://json.org/java/

                      【讨论】:

                        【解决方案14】:

                        实际上,我找到了一个简单的答案,Jst 将对象添加到 String Builder 而不是 String 工作 ;)

                        StringBuilder jsonString= new StringBuilder.append("http://www.json-.com/j/cglqaRcMSW?=4");    
                        JSON json= new JSON(jsonString.toString);
                        

                        【讨论】:

                        • 我很确定这是不正确的。你能解释一下这究竟是如何解决你的问题的吗?它仍然没有打开连接以从服务器检索 JSON,它不是有效的 JSON,它是一个 URL。此外, new StringBuilder.append 不是有效的 Java 语法。由于您不接受我的回答,我想知道为什么这样会更好,谢谢。
                        • 这里的代码不正确,为什么不用阿萨夫的答案?
                        • 使用字符串生成器究竟是如何解决问题的?您仍在传递一个 URL 并尝试从中创建一个 JSON 对象,这是不正确的。
                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2017-02-20
                        • 1970-01-01
                        • 1970-01-01
                        • 2017-06-06
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多