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

标签 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"

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

最佳答案

您可以将其解析为一个有详细记录的对象。但是,如果您不想围绕某些响应构建整个对象框架,您可以使用它们的通用 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

关于Java:JSON(Gson)从JSON字符串获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24023545/

相关文章:

java - Android:位图到字节数组并返回:SkImageDecoder::Factory 返回 null

php - mysql中的json数据

ios - 为什么从此 URL 检索数据返回 nil?

python - 如何使用机器人框架在终端中执行命令?

javascript - 如何使用 jquery 访问 JSON 嵌套数组

java - 听法

java - 你能帮我找出这段代码中的错误吗?我似乎不明白为什么它不起作用?

java - JVM 可以看到多少代码?

Python - 使用 "astype"的 Pandas 列类型转换不起作用

python - 我如何将变量 names_and_ranks 分配给列表,每个元素等于城市名称及其对应的排名?