将JSON键值对转换为JSON Array Android

时间:2013-05-09 05:22:28

标签: android json encode key-value arrays

我有一组键值对,如下所示:

{
  "320x240":"http:\/\/static.example.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_320x240.jpg",
  "300x225":"http:\/\/static.zigwheels.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_300x225.jpg",
  "200x150":"http:\/\/static.zigwheels.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_200x150.jpg"
}

我目前正在做的是:

   try {

      images_object = new JSONObject(imageList);//imageList is a String of the above array //of key value pairs

            Iterator<?> keys = images_object.keys();
            String string_images = "";
           if(keys.hasNext()) {
               String key = (String)keys.next();
                String value = (String)images_object.get(key);
                string_images = "[" + value;  
           }
            while( keys.hasNext() ){
                String key = (String)keys.next();
                String value = (String)images_object.get(key);
                string_images = string_images + "," + value;

            }
            string_images = string_images + "]";
            String encoded_json_string = JSONObject.quote(string_images);
            images = new JSONArray(encoded_json_string);//images is of type JSONArray but it is null
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

但是,图像是NULL。为什么?我错过了什么?

1 个答案:

答案 0 :(得分:4)

您可以将JSONObject中当前JSONArray的所有值设为:

Iterator<String> keys = images_object.keys();
JSONArray images = new JSONArray();
while( keys.hasNext() ){
    String key = keys.next();
    String value = images_object.optString(key);
    //add value to JSONArray from JSONObject
    images.put(value);
}

编辑

简化解决方案是使用images_object.names()获取密钥,您可以将JSONArray个密钥传递给toJSONArray方法,以获取JSONArray

JSONArray keys=images_object.names();
JSONArray values=images_object.toJSONArray(keys);

总结简化解决方案是:

JSONArray images=images_object.toJSONArray(images_object.names());