在我的Android App中解析此JSON数据时遇到问题:
[{"personid":20,"personName":"Ross Gallagher update3","email":"ross_gallagher@rossgallagher.co.uk","birthday":{"date":"2013-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"anniversary":{"date":"1900-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"Credit":2}]
我得到的错误是:
W/System.err: org.json.JSONException: Value [{"birthday":{"date":"2013-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"anniversary":{"date":"1900-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"email":"ross_gallagher@rossgallagher.co.uk","personName":"Ross Gallagher update8","Credit":2,"personid":20}] of type org.json.JSONArray cannot be converted to JSONObject
我的JSON解析器代码是:
public JSONObject getJSONFromUrl(String url)
{
HttpEntity httpEntity = null;
JSONObject respObject = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(httpEntity != null){
try {
respObject = new JSONObject(EntityUtils.toString(httpEntity));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//....
}
// return JSON
return respObject;
}
我只需要从这个JSON对象中提取生日详细信息以及姓名,电子邮件,信用和周年纪念日。
任何建议都将不胜感激!
答案 0 :(得分:1)
更改
respObject = new JSONObject(EntityUtils.toString(httpEntity));
到
respObject = new JSONArray(EntityUtils.toString(httpEntity));
ofcourse respObject必须是JSONArray
答案 1 :(得分:0)
问题在于您的JSON字符串。您需要移除方形支架 [] 。 方形支架用于引用数组元素。 JSON解析器将尝试将其转换为数组对象,因为json数据位于square braket内。
如果对你有帮助,请接受我的回答。
答案 2 :(得分:-1)
因为你试图解析的对象实际上是一个JSONArray而不是JSONObject ..所以你从那个JSONArray获得JSONObject
JSONArray jsonArray = new JSONArray(EntityUtils.toString(httpEntity));
JSONOject jsonObject = jsonArray.getJSONObject(0);
从这个jsonObject你会得到生日详情...