简体   繁体   中英

Convert Json String to JsonObject Object

I have the following JSON:

{
     "insertId":"qxdo1se4pjcw",
     "logName":"projects,
      "protoPayload":{
          "type":"type.googleapis.com/google.cloud.audit.AuditLog",
          "authenticationInfo":{
             "principalEmail":"gserviceaccount.com"
          },
          "authorizationInfo":[
             {
                "granted":true,
                "permission":"bigquery.tables.updateData",
                "resource":"metrics_event",
                "resourceAttributes":{
                   
                }
             }
          ]
    }

I want to convert this to JSON object so later we can easily refer to each object My code:

 String msg = message.getData().toStringUtf8();
 JsonParser pa = new JsonParser();
 JsonObject obj = (JsonObject) pa.parse(msg);

I can access the element using get method but how to access the element which are nested for example

obj.get("protoPayload" ) is working fine but how to access type

similar to obj.get("protoPayload").get("type")

Use plain JSON from org.json

JSONObject json=new JSONObject(String source);

This would convert valid JSON string to JSON Object.

If you want to access nested object within JSON and you already know the "key",then you can use the following.

JSONObject extends a HashMap, so you can simply use it as a HashMap:

JSONObject jsonChildObject = (JSONObject)jsonObject.get("protoPayload");
for (Map.Entry in jsonChildOBject.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Use obj.getJsonObject("protoPayload").get("type")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM