我想根据JSON对象的键值检索所有值。在java中使用JSON对象Hashmap
这里是我的样品JSON:
[{
"zip":544,
"type":"UNIQUE",
"primary_city":"Holtsville",
"acceptable_cities":"",
"unacceptable_cities":"Irs Service Center",
"state":"NY",
"county":"Suffolk County",
"timezone":"America/New_York",
"area_codes":"631",
"latitude":40.81,
"longitude":-73.04,
"world_region":"NA",
"country":"US",
"decommissioned":0,
"estimated_population":0,
"notes":""
},
{
"zip":601,
"type":"STANDARD",
"primary_city":"Adjuntas",
"acceptable_cities":"",
"unacceptable_cities":"Colinas Del Gigante, Jard De Adjuntas, Urb San Joaquin",
"state":"PR",
"county":"Adjuntas",
"timezone":"America/Puerto_Rico",
"area_codes":"787,939",
"latitude":18.16,
"longitude":-66.72,
"world_region":"NA",
"country":"US",
"decommissioned":0,
"estimated_population":0,
"notes":""
}]
因此,基于我的邮政编码为重点,我想要检索的所有其他值。
我曾尝试过使用单个键值对的JSON对象,但不知道如何为上面的JSON对象做同样的事情。
这是我的一个键 - 值对
成功运行代码import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONObject;
public class map {
public static void main(String[] args) {
String t = "{\"A\":\"A1\",\"B\":\"B1\",\"C\":\"C1\"}";
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while(keys.hasNext()){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : "+jObject);
System.out.println("map : "+map.get("A"));
}
}
输出:
json : {"A":"A1","B":"B1","C":"C1"}
map : A1
的如何做到这一点有什么建议?
我已经看过几个以前的答案,但没有一个解决这个问题?
是你的JSON对象数组? –
yes..edited JSON在我的问题更清晰 – x0v
请。检查我的答案,这将有助于。 –