这是我的php文件提供的JSON:
[{"id":"408","punktezahl":"15","name":"testname","email":"hsksjs","datum":"24.01.14 17:11","wohnort":"Vdhdhs","newsletter":"J"}]
当我尝试像这样访问JSON对象时
public void connect(){
System.out.println("%%%%%%%%%%%%%%%%%1" );
Thread t = new Thread(){
@Override
public void run() {
try {
System.out.println("%%%%%%%%%%%%%%%%%2" );
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
String urlString = "http://url";
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
System.out.println("%%%%%%%%%%%%%%%%%3" );
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
//return the JSON response
JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("output");
String name = userDetails.getString("name");
System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
}
}catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
我收到以下错误:
01-24 18:18:21.746: W/System.err(20673): org.json.JSONException: Value [{"id":"408","datum":"24.01.14 17:11","punktezahl":"15","email":"hsksjs","newsletter":"J","wohnort":"Vdhdhs","name":"testname"}] of type org.json.JSONArray cannot be converted to JSONObject
01-24 18:18:21.746: W/System.err(20673): at org.json.JSON.typeMismatch(JSON.java:111)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:159)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:172)
01-24 18:18:21.746: W/System.err(20673): at com.wuestenfest.jagdenwilli.Highscore_zeigen$1.run(Highscore_zeigen.java:82)
我的错误在哪儿?
答案 0 :(得分:2)
您的回复是JSONArray
而不是JSOnObject
。
所以改变
JSONObject parentObject = new JSONObject(response);
到
JSONArray jsonarray = new JSONArray(response);
你的JSON
[ // json array node
{ // jsson onject npode
"id": "408",
"punktezahl": "15",
"name": "testname",
"email": "hsksjs",
"datum": "24.01.14 17:11",
"wohnort": "Vdhdhs",
"newsletter": "J"
}
]
在上面的json中我没有看到任何json对象output
。所以
JSONObject userDetails = parentObject.getJSONObject("output");
也错了。
解析
JSONArray jsonarray = new JSONArray(response);
JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
String name= jb.getString("name");
答案 1 :(得分:1)
问题就像异常描述的那样:你试图将你的响应对象解析为JSONObject,但它实际上是一个JSONArray(如方括号所示)。相反,将其解析为JSONArray,并从数组中获取第一个元素,这将是您想要的JSONObject。