在Android中操作JSON数组

时间:2013-08-14 18:12:46

标签: java android json

我有一个JSON数组:

[{"value":01,"label":"One"},{"value":5,"label":"Five"}]

如何将所有'值'转换为int数组,将所有'标签'转换为字符串数组?

我希望得到以下内容:

values = [1,5];
labels = ["One", "Five"];

3 个答案:

答案 0 :(得分:0)

// Parse the JSON string into an array:
JSONArray array = new JSONArray("[{\"value\":01,\"label\":\"One\"},{\"value\":5,\"label\":\"Five\"}]");
// Get the length or our array (in this case, the length will be equal to 2):
int len = array.length();
// Create the two arrays to store our results
int[] values = new int[len];
String[] labels = new String[len];
// Loop through the array retrieving every object and in turn saving the values to our result arrays:
for (int index = 0; index < len; index++) {
    JSONObject curr = array.getJSONObject(i);
    values[index] = curr.getInt("value");
    labels[index] = curr.getString("label");
} 

答案 1 :(得分:0)

您可以使用droidQuery帮助映射值,然后将它们放入所需的数组中:

Object[] objs = $.makeArray(yourJSONArray);//replace "yourJSONArray" with your variable name
String[] labels = new String[objs.length];
int[] values = new int[objs.length];
for (int i = 0; i < objs.length; i++) {
    Object o = objs[i];
    Map<String, ?> map = $.map((JSONObject) o);
    for (Entry<String, ?> e : map.entrySet()) {
        labels[i] = e.getKey();
        values[i] = Integer.parseInt(e.getValue().toString());
    }
}

答案 2 :(得分:0)

使用GSON,它使用反射将值从JSON映射到对象