Reputation: 16780
I have an array of key-value pairs like this:
{
"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"
}
What I'm doing currently is this:
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();
}
But, images, is NULL. Why's that? What am I missing?
Upvotes: 2
Views: 7004
Reputation: 132972
you can get all values from current JSONObject
in JSONArray
as:
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);
}
EDIT
Simplified solution is get the keys with images_object.names()
and you can pass JSONArray
of keys to toJSONArray
method to get the value with respect to keys in JSONArray
JSONArray keys=images_object.names();
JSONArray values=images_object.toJSONArray(keys);
To Summing up simplified solution is:
JSONArray images=images_object.toJSONArray(images_object.names());
Upvotes: 4