【问题标题】:Java: JSON (Gson) get values from JSON string [duplicate]Java:JSON(Gson)从JSON字符串中获取值[重复]
【发布时间】:2014-06-03 19:38:37
【问题描述】:

我有一个 JSON 字符串打印为:

{
  "result":"_error",
  "invokeId":2,
  "data":{
     "timestamp":1.401824129758E12,
     "rootCause":{
        "message":"Wrong client version for server",
        "localizedMessage":"Wrong client version for server",
        "rootCauseClassname":"login.impl.ClientVersionMismatchException",
        "substitutionArguments":[
           "4.9",
           "4.8.14_05_16_17_02"
        ],
        "errorCode":"LOGIN-0001"
     },
     "headers":{

     },
     "correlationId":"00E36368-6158-CD63-56CA-4F39493E8ED3",
     "faultCode":"Server.Processing",
     "messageId":"D8424EAD-8D0B-5441-820B-775B99812CFD",
     "faultString":"login.impl.ClientVersionMismatchException : Wrong client version for server",
     "timeToLive":0.0,
     "clientId":"D8424E8B-5F0F-1ECD-C29F-C6440488B0FC",
     "destination":"loginService"
  },
  "version":0
}

我知道如何在 Python 中做到这一点,所以我会展示它。

x 成为 Python 中的 JSON 对象作为字典。 x['data']['rootCause']['substitutionArguments'] 会得到我"4.8.14_05_16_17_02"

如何在 Java 代码中获得"4.8.14_05_16_17_02"?我使用Gson 作为我的Java JSON 库。

【问题讨论】:

  • 你是如何使用 Gson 的?
  • 我使用 Gson 使用 toJson(...) 函数打印我的对象。
  • 所以你有一个对象层次结构。该层次结构中的substitutionArguments 在哪里?取回它。
  • 我要问的是,如何将我的 JSON 字符串转换为 HashMap(相当于 Java 的字典)?
  • 我要问的是,到目前为止,您为使用 Gson 检索该字段做了什么?向我们展示您的尝试。 Gson 与 POJO 一起用于与 JSON 之间的映射。您的 POJO 在哪里/什么?

标签: java python json


【解决方案1】:

您可以将其解析为一个有据可查的对象。但是,如果您不想围绕某些响应构建一个完整的对象框架,您可以使用它们的通用 JsonArrayJsonObject 类来遍历您的 json 字符串。

// this is just your json string.
String yourJson = "{\"result\":\"_error\",\"invokeId\":2,\"data\":{\"timestamp\":1.401824129758E12,\"rootCause\":{\"message\":\"Wrong client version for server\",\"localizedMessage\":\"Wrong client version for server\",\"rootCauseClassname\":\"login.impl.ClientVersionMismatchException\",\"substitutionArguments\":[\"4.9\",\"4.8.14_05_16_17_02\"],\"errorCode\":\"LOGIN-0001\"},\"headers\":{},\"correlationId\":\"00E36368-6158-CD63-56CA-4F39493E8ED3\",\"faultCode\":\"Server.Processing\",\"messageId\":\"D8424EAD-8D0B-5441-820B-775B99812CFD\",\"faultString\":\"login.impl.ClientVersionMismatchException : Wrong client version for server\",\"timeToLive\":0.0,\"clientId\":\"D8424E8B-5F0F-1ECD-C29F-C6440488B0FC\",\"destination\":\"loginService\"},\"version\":0}";
// create a parser
JsonParser parser = new JsonParser();
// parse then get your root node as a JsonObject
JsonObject obj = parser.parse(yourJson).getAsJsonObject();

// traverse your object
JsonArray subArgs = obj.get("data").getAsJsonObject()
        .get("rootCause").getAsJsonObject()
        .get("substitutionArguments").getAsJsonArray();

// because the get(1) returns a JsonElement you will need to use getAsString 
// to retrive the actual results
System.out.println(subArgs.get(1).getAsString()); // 4.8.14_05_16_17_02

【讨论】:

    【解决方案2】:

    如何在 Java 代码中获得“4.8.14_05_16_17_02”?

    如果您只对 JSON 中的特定值感兴趣,请尝试以下代码。只需创建一些在某种程度上复制 JSON 字符串的 POJO 类。

    这里使用Gson#fromJson()方法将JSON字符串转换为JAVA对象。

    注意:在 POJO 类中添加更多变量(区分大小写)以从 JSON 字符串中获取更多值。

    示例代码:

    class ExeceptionJSONObject {
        private Data data;
        // getter and setter
    }
    
    class Data {
        private RootCause rootCause;
        // getter and setter
    }
    
    class RootCause {
        private ArrayList<String> substitutionArguments;
        // getter and setter
    }
    
    ...
    
    // Here is the code
    ExeceptionJSONObject object = new Gson().fromJson(json, ExeceptionJSONObject.class);
    
    System.out.println(object.getData().getRootCause().getSubstitutionArguments().get(1));
    
    System.out.println("\nPretty format of the converted object\n");
    System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(object));
    

    输出:

    4.8.14_05_16_17_02
    
    Pretty format of the converted object
    
    {
      "data": {
        "rootCause": {
          "substitutionArguments": [
            "4.9",
            "4.8.14_05_16_17_02"
          ]
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      假设您有一个 Response 类,其中包含 JSon 中每个字段的字段,您可以调用

      Gson gson = new Gson();
      Response r = gson.fromJson(Response.class, "YourJsonString");
      

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 1970-01-01
        • 2014-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-08
        • 1970-01-01
        相关资源
        最近更新 更多