【问题标题】:JSON parser in Java using MapJava中使用Map的JSON解析器
【发布时间】:2018-02-07 01:36:51
【问题描述】:

我正在尝试使用 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 文件的 sn-p。我正在尝试在属性对象中获取 NAME。

{
    "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."
            },

【问题讨论】:

    标签: java json parsing mapping


    【解决方案1】:

    (Map&lt;String, String&gt;) jsonObject.get("properties"),您正试图从您的“根”对象(由jsonObject 持有)访问properties,而没有这样的密钥。您可能想从features 数组持有的对象中获取该键的值。您已经为该数组创建了迭代器,但您从未使用它来获取它所持有的元素。你需要类似的东西

    while (iter.hasNext()) {
        JSONObject tmpObject = (JSONObject) iter.next();
        ...
    }
    

    并在该tmpObject 上致电get("properties")

    【讨论】:

    • @VincentArrage 欢迎您。顺便说一句,你应该看看How to efficiently iterate over each entry in a 'Map'?。如果你想修改地图(比如删除一些条目),显式使用迭代器很好。如果你只是想打印它的元素代码,使用 for-each 可能更容易编写和维护。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2022-01-20
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    相关资源
    最近更新 更多