JSON parsing in android: No value for x error

2020-02-13 02:59发布

问题:

Here is the code I'm using inside my 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;

This returns a string result and in my onPostExecute method I try to parse that input string:

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"));

As soon as it reaches makeEdit.setText it throws an error - no value for make. I'm still very new to android, so don't send death threats if there was some obvious error. The input text is the following JSON string:

{"GetJSONObjectResult":{"make":"Ford","model":"Focus","plate":"XXO123GP","year":2006}}

回答1:

No value for x error message is pretty common when dealing with JSON. This usually resulted by overlooked code.

usually, when dong JSON, I try to see the human readable structure first. For that, I usually use JSONViewer.

In your case, the structure is something like this:

You see that make is within another object called GetJSONObjectResult. Therefore, to get it, you must first get the container object first:

JSONObject vehicle = ((JSONObject)new JSONObject(result)).getJSONObject("GetJSONObjectResult");
//a more easy to read
JSONObject container = new JSONObject(result);
JSONObject vehicle = container.getJSONObject("GetJSONObjectResult");

and finally use the object to get make:

makeEdit.setText(vehicle.getString("make"));
plateEdit.setText(vehicle.getString("plate"));
modelEdit.setText(vehicle.getString("model"));
yearEdit.setText(vehicle.getString("year"));


回答2:

Your JSON Object contains itself a JSONObject. To acces to your data, you have to do like this:

vehicle.getJSONObject("GetJSONObjectResult").getString("make");