我想根據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
請。檢查我的答案,這將有助於。 –