将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)

代码:

试块内部

            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();
        }

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

使用JsonArray代替JsonObject,例如:

try {
    JSONArray myJsonArray = new JSONArray(result);
} catch (JSONException e) {
    // log Error
}

我认为您从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();
}

最新更新