解析json数据时如何判断key是否存在

How to find out if key exists or not when parsing json data

我正在尝试使用 Java.My 解析 json 文件 json 给定的文件格式 below.I 如果操作是 [=19],则试图打印一条消息=] 并打印 performed_at。但是,下面的代码没有输出。

提前感谢您的建议和您的time.Appreciate。

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

        }
    }

你应该得到 JsonObject,而不是 Map:

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

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

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

最后你应该使用 has() 来检查你想要的属性:

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

你应该嵌套得更深一层才能得到注释。

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