这是我在AsyncTask中使用的代码
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
result = new String(buffer);
return result;
这会返回一个字符串结果,在我的onPostExecute方法中,我尝试解析该输入字符串:
JSONObject vehicle = new JSONObject(new String(result));
makeEdit.setText(vehicle.getString("make"));
plateEdit.setText(vehicle.getString("plate"));
modelEdit.setText(vehicle.getString("model"));
yearEdit.setText(vehicle.getString("year"));
一旦到达makeEdit.setText就会抛出错误 - 没有make的值。我对android很新,所以如果有一些明显的错误,不要发送死亡威胁。输入文本是以下JSON字符串:
{"GetJSONObjectResult":{"make":"Ford","model":"Focus","plate":"XXO123GP","year":2006}}
答案 0 :(得分:9)
No value for x error
消息非常常见。这通常是由于被忽视的代码造成的。
通常,当使用dong JSON时,我首先尝试查看人类可读结构。为此,我通常使用JSONViewer。
在您的情况下,结构是这样的:
您看到make
位于另一个名为GetJSONObjectResult
的对象中。因此,要获得它,首先必须先获取容器对象:
JSONObject vehicle = ((JSONObject)new JSONObject(result)).getJSONObject("GetJSONObjectResult");
//a more easy to read
JSONObject container = new JSONObject(result);
JSONObject vehicle = container.getJSONObject("GetJSONObjectResult");
最后使用该对象获取make
:
makeEdit.setText(vehicle.getString("make"));
plateEdit.setText(vehicle.getString("plate"));
modelEdit.setText(vehicle.getString("model"));
yearEdit.setText(vehicle.getString("year"));
答案 1 :(得分:3)
您的JSON对象本身包含一个JSONObject。要访问您的数据,您必须这样做:
vehicle.getJSONObject("GetJSONObjectResult").getString("make");