2

我有一个这样的键值对数组:

{
  "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。为什么?我错过了什么?

4

1 回答 1

4

您可以从 current JSONObjectin 中获取所有值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());
于 2013-05-09T05:31:01.087 回答