java - 如何读取 JSON 数组,Android Java

标签 java android arrays json

我需要读取这个 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 数组的方法..

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

关于java - 如何读取 JSON 数组,Android Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35610470/

相关文章:

java - 减小 jar 文件大小

java - Android-几天后运行后出现代码错误

javascript - 在 Javascript 中填充数组

c - 如何以指针格式访问结构内的数组?

java - Volley deliverResponse 未被调用

php - 如何在cakephp中的另一个条件中使用条件

java - 音频输入流不工作

java - hyperjaxb3 : Enumeration questions

java - 如何保护客户端/服务器套接字通信

android - 如何使 Android TV 可以搜索应用内容