有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将JSONObject转换为JSONArray错误

错误:

W/System.err﹕ org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)

W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:158)

W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:171)

代码:

在try街区内

            post.setEntity(new UrlEncodedFormEntity(data_to_send));
            HttpResponse httpResponse = client.execute(post);

            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);


            JSONObject jsonObject = new JSONObject(result);

            if(jsonObject.length() == 0)
            {
                retunedContact = null;

            }
            else
            {
                String name,email;
                name = null;
                email=null;

                if(jsonObject.has("name"))
                    name = jsonObject.getString("name");
                if(jsonObject.has("email"))
                    email =jsonObject.getString("email");

                retunedContact = new Contact(name , email , contact.username , contact.password);

            }


        catch(Exception e)
        {
            e.printStackTrace();
        }

共 (2) 个答案

  1. # 1 楼答案

    你的结果似乎是类似JSONArray[..],而不是类似JSONObject{..}

    使用JsonArray代替JsonObject,例如:

    try {
        JSONArray myJsonArray = new JSONArray(result);
    } catch (JSONException e) {
        // log Error
    }
    
  2. # 2 楼答案

    我想你从api得到的格式是什么

    [
      {
         "somekey":"somevalue",
         "somekey2":"somevalue2"
      },
    
      {
         "somekey":"somevalue",
         "somekey2":"somevalue2"
      }
    ]
    

    那么你应该知道这种格式是JSONArray而不是JSONObject。所以,最好尝试这两种代码中的任何一种

    JSONParser parser = new JSONParser() 
    JSONObject jsonObject = (JSONArray)parser.parse(result);
    

    或者

    try {
        JSONArray obj_JSONArray= new JSONArray(result);
    } catch (JSONException e) {
        e.printStackTrace();
    }