2013-05-09 56 views
2

我有鍵值對像這樣的數組:轉換JSON鍵值對成JSON數組的Android

{ 
    "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(); 
     } 

但是,圖像, 一片空白。爲什麼?我錯過了什麼?

+0

因爲您沒有創建有效的JSON。 'string_images'絕不會像有效的JSON那樣需要引用字符串。 – 2013-05-09 05:28:19

+0

你能告訴我什麼是錯的嗎?我也嘗試刪除方括號。 – Namratha 2013-05-09 05:31:04

+0

@Namratha下面的答案是什麼問題?你嘗試過嗎? – Pragnani 2013-05-09 07:07:49

回答

4

你可以在JSONArray從當前JSONObject所有值:

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()拿到鑰匙了,你可以通過按鍵JSONArraytoJSONArray方法來獲得相對於鍵的值JSONArray

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

總結簡化的解決方案是:

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

方法add(String)對於JSONArray類型是未定義的。 – Namratha 2013-05-09 05:35:01

+0

@Namratha:那麼你可以使用JSONArray.put。看到我的編輯答案 – 2013-05-09 05:36:02

+0

好的,謝謝。但是,你能告訴我我的方法有什麼問題嗎? – Namratha 2013-05-09 05:37:26