简体   繁体   English

将 Json 字符串转换为 JsonObject Object

[英]Convert Json String to JsonObject Object

I have the following JSON:我有以下 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:我想将其转换为 JSON object 以便稍后我们可以轻松参考每个 object 我的代码:

 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我可以使用 get 方法访问元素,但是如何访问嵌套的元素,例如

obj.get("protoPayload" ) is working fine but how to access type obj.get("protoPayload" ) 工作正常,但如何访问type

similar to obj.get("protoPayload").get("type")类似于obj.get("protoPayload").get("type")

Use plain JSON from org.json使用来自 org.json 的普通 JSON

JSONObject json=new JSONObject(String source);

This would convert valid JSON string to JSON Object.这会将有效的 JSON 字符串转换为 JSON Object。

If you want to access nested object within JSON and you already know the "key",then you can use the following.如果您想访问 JSON 内的嵌套 object 并且您已经知道“密钥”,那么您可以使用以下内容。

JSONObject extends a HashMap, so you can simply use it as a HashMap: JSONObject 扩展了 HashMap,因此您可以简单地将其用作 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")使用obj.getJsonObject("protoPayload").get("type")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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