简体   繁体   中英

How Read JSON Array, Android Java

I need to read this JSON array :

[{
"1":{"id":"0","name":"first"},
"2":{"id":"1","name":"second"}
}]

I use this code

    JSONObject jsonObject = null;
    for(int i=0; i < array.length(); i++)
    {
        try 
        {
            jsonObject = array.getJSONObject(i);
            System.out.println("Data: " + jsonObject.getString("id"));
        }
        catch (JSONException e) 
        {
            Log.e("Get Data from JSON Array ..", "Error: " + e.getMessage());
        }
    }

But the array length = 1 always and the error appear : no value for id

The method to return JSON Array ..

    public static JSONArray getJSONArrayFromUrl(String url)
{
    String str = "{\"Array\":["; // I add it because the JSON return from the site not contains root ..
    HttpResponse response;
    HttpClient myClient = new DefaultHttpClient();
    HttpPost myConnection = new HttpPost("url);        
    try 
    {
        response = myClient.execute(myConnection);
        str += EntityUtils.toString(response.getEntity(), "iso-8859-1") + "]}";
    }
    catch (ClientProtocolException e) {
        Log.e("Client Protocol Exception", "Error: " + e.getMessage());
    } 
    catch (IOException e) {
        Log.e("IO Exception", "Error: " + e.getMessage());
    }

    JSONObject obj = null;
    JSONArray array = null;

    try  {
        obj = new JSONObject(str);
        array = obj.getJSONArray("Array");
    } 
    catch (JSONException e) {
        Log.e("JSON Exception", "Error: " + e.getMessage());
    }

    return array;
}

How to solve it or how to read the JSON text ..

Thanks ,,

At first you need to create a class like this one:

public class ExampleClass { 
    int id; 
    String name; 
}

And then you call it in your try:

Gson gson = new Gson(); 
Type listOfTestObject = new TypeToken<ArrayList<ExampleClass>>() { }.getType(); 
ArrayList<ExampleClass> arrayInJSON = gson.fromJson(exampleJSONObject, listOfTestObject);

Then, you can use the response from JSON to get the size:

arrayInJSON.size();

It is an array with one element on it [{ "1":{"id":"0","name":"first"}, "2":{"id":"1","name":"second"} }]

  becouse it look like [{...}] 

  here {...} is a map of 2 elements it is not array 
  jsonObject.getString("1").getString("id") in your code should return     what you need 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM