簡體   English   中英

如何閱讀JSON數組,Android Java

[英]How Read JSON Array, Android Java

我需要閱讀以下JSON數組:

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

我用這個代碼

    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());
        }
    }

但是數組長度始終為1,並且會出現錯誤:id無值

返回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;
}

如何解決它或如何讀取JSON文本..

謝謝 ,,

首先,您需要創建一個像這樣的類:

public class ExampleClass { 
    int id; 
    String name; 
}

然后您可以嘗試調用它:

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

然后,您可以使用JSON的響應來獲取大小:

arrayInJSON.size();

它是一個帶有一個元素的數組[{“ 1”:{“ id”:“ 0”,“ name”:“ first”},“ 2”:{“ id”:“ 1”,“ name”: “第二”}}]

  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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM