Java: JSON (Gson) 从 JSON 字符串中获取值

0 投票
3 回答
2661 浏览
提问于 2025-04-18 08:28

我有一个打印出来的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是那个JSON对象,在Python中它就像一个字典。通过x['data']['rootCause']['substitutionArguments'],我可以得到"4.8.14_05_16_17_02"这个值。

那么在Java代码中,我该怎么获取"4.8.14_05_16_17_02"呢?我在Java中使用的是Gson这个库来处理JSON。

3 个回答

-1

假设你有一个叫做 Response 的类,这个类里面有和 JSON 中每个字段对应的属性,你只需要调用一下就可以了。

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

我怎么在Java代码中得到“4.8.14_05_16_17_02”?

如果你只对JSON中的特定值感兴趣,可以试试下面的代码。简单来说,你需要创建一些POJO类,这些类大致上是JSON字符串的复制品。

这里使用了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"
      ]
    }
  }
}
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

撰写回答