我需要读取这个 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/