[英]JSON parser in Java using Map
我正在嘗試使用org.json.simple庫解析json文件,並且在嘗試使用Map實例化迭代器時出現空指針異常。
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("wadingpools.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
JSONArray featuresArray = (JSONArray) jsonObject.get("features");
Iterator iter = featuresArray.iterator();
while (iter.hasNext()) {
Map<String, String> propertiesMap = ((Map<String, String>) jsonObject.get("properties"));
Iterator<Map.Entry<String, String>> itrMap = propertiesMap.entrySet().iterator();
while(itrMap.hasNext()){
Map.Entry<String, String> pair = itrMap.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
這是JSON文件的一部分。 我正在嘗試在屬性對象中獲取名稱。
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [{
"type": "Feature",
"properties": {
"PARK_ID": 393,
"FACILITYID": 26249,
"NAME": "Wading Pool - Crestview",
"NAME_FR": "Pataugeoire - Crestview",
"ADDRESS": "58 Fieldrow St."
},
在(Map<String, String>) jsonObject.get("properties")
您嘗試從不具有此類鍵的 “ root”對象(由jsonObject
)訪問properties
。 您可能想從features
數組持有的對象中獲取該鍵的值。 您已經為該數組創建了迭代器,但是從未使用它來獲取該數組所持有的元素。 你需要類似的東西
while (iter.hasNext()) {
JSONObject tmpObject = (JSONObject) iter.next();
...
}
並在該tmpObject
上調用get("properties")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.