首页 > 解决方案 > 将 Json 字符串转换为 JsonObject 对象

问题描述

我有以下 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":{
                   
                }
             }
          ]
    }

我想将其转换为 JSON 对象,以便稍后我们可以轻松引用每个对象我的代码:

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

我可以使用 get 方法访问元素,但是如何访问嵌套的元素,例如

obj.get("protoPayload") 工作正常,但如何访问type

如同obj.get("protoPayload").get("type")

标签: javajson

解决方案


使用来自 org.json 的纯 JSON

JSONObject json=new JSONObject(String source);

这会将有效的 JSON 字符串转换为 JSON 对象。

如果您想访问 JSON 中的嵌套对象并且您已经知道“密钥”,那么您可以使用以下内容。

JSONObject 扩展了 HashMap,因此您可以简单地将其用作 HashMap:

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

推荐阅读