gpt4 book ai didi

android - 将JSON键值对转换成JSON数组Android

转载 作者:搜寻专家 更新时间:2023-11-01 08:04:27 26 4
gpt4 key购买 nike

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

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

最佳答案

您可以从 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() 获取键,您可以将键的 JSONArray 传递给 toJSONArray 方法以获取值关于 JSONArray

中的键
JSONArray keys=images_object.names();
JSONArray values=images_object.toJSONArray(keys);

总结简化的解决方案是:

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

关于android - 将JSON键值对转换成JSON数组Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16454921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com