[英]How Read JSON Array, Android Java
I need to read this JSON array : 我需要阅读以下JSON数组:
[{
"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 但是数组长度始终为1,并且会出现错误:id无值
The method to return JSON Array .. 返回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 .. 如何解决它或如何读取JSON文本..
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: 然后,您可以使用JSON的响应来获取大小:
arrayInJSON.size();
It is an array with one element on it [{ "1":{"id":"0","name":"first"}, "2":{"id":"1","name":"second"} }] 它是一个带有一个元素的数组[{“ 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.