我有JSON:
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
我的代码:
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
我不知道在“课程”之后获得数组编号。
答案 0 :(得分:0)
courses
是JSONArray
,所以你可以这样做:
JSONArray coursesArray = linksObject.getJSONArray("courses");
<强>更新强>
从coursesArray
获取值:
int value = coursesArray.optInt(position);
答案 1 :(得分:0)
我会使用HashMaps。这里有一个例子(creating Hashmap from a JSON String )如何从JSON字符串中获取它。
特别是对于&#34;课程&#34;,一旦你被解析到那里,我会使用HashMap<String,List<Integer>>
答案 2 :(得分:0)
几乎就在那里。一旦你得到你的
JSONArray courses = object.getJSONArray("courses");
简单地遍历其值:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
以上将这些数字保存在一个数组中并打印出来:
号码:15
数字:30
号码:46
号码:47
请记住,“课程”键可能不存在,数组可能是空的等等。