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

时间:2014-06-03 19:38:38

标签: java python json

我将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"?我使用Gson作为我的Java JSON库。

3 个答案:

答案 0 :(得分:1)

  

我如何得到" 4.8.14_05_16_17_02"在Java代码?

如果您只对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 :(得分: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 :(得分:-1)

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

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