解析json数据时如何找出键是否存在

时间:2019-05-11 13:01:35

标签: java json json-simple

我正在尝试使用Java解析json文件。我的json文件格式如下所示。如果操作是“便笺”,则尝试打印一条消息并打印Performed_at。但是,以下代码没有输出。

提前感谢您的建议和时间。不胜感激。

 {
"data": {
    "name": "John"

},
"activities_data": [{
        "performed_at": "April",
        "id": 630,

        "action": {
            "address": "N/A",

            "issue_type": "F A"

        }
    },
    {
        "performed_at": "March",
        "id": 687,

        "action": {
            "note": {
                "id": 26519,
                "type": 4
            }
        }
    }
]
}

Java代码:

    import java.io.FileReader;
    import java.io.IOException;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
    import java.io.Reader;
    import java.util.Iterator;
    import java.util.Map; 


    public class Readjsonfile {

    public static void main(String[] args) throws Exception {
        JSONParser parser = new JSONParser();
        JSONObject ticketObject = (JSONObject) parser.parse(new FileReader("activity.json"));




        JSONArray jsonArray= (JSONArray) ticketObject.get("activities_data");


        for(int i=0; i<jsonArray.size(); i++){

            Map activityobject  = ((Map)jsonArray.get(i));
            System.out.println(activityobject);
            if (activityobject.containsKey("note"))
                {  
                System.out.println("its a note");
                    \\and print performed_at here
                }
            }   

        }
    }

2 个答案:

答案 0 :(得分:1)

您应该获得JsonObject,而不是Map

JSONObject activityobject  = ((JSONObject) jsonArray.get(i));

然后,您必须加载JSON的action部分(您不能递归查找属性:

JSONObject actionObject  = ((JSONObject) activityobject.get('action'));

最后,您应该使用has()来检查所需的属性:

if (actionObject.has('note')) {

答案 1 :(得分:1)

您应该嵌套更深的级别以获得音符。

for(int i=0; i<jsonArray.size(); i++){
    Map activityobject  = ((Map)jsonArray.get(i));
    System.out.println(activityobject);
    if (activityobject.containsKey("action")) {
        Map actionObject  = ((Map)activityobject.get("action"));
        if (actionObject.containsKey("note")) {
            System.out.println("its a note");
            System.out.println("note" + actionObject.get("note"));
            System.out.println("Performed at " + activityobject.get("performed_at"));
        }
    }
}

输出

{"performed_at":"April","action":{"address":"N\/A","issue_type":"F A"},"id":630}
{"performed_at":"March","action":{"note":{"id":26519,"type":4}},"id":687}
its a note
note{"id":26519,"type":4}
Performed at March