我有一个 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 库。
最佳答案
您可以将其解析为一个有详细记录的对象。但是,如果您不想围绕某些响应构建整个对象框架,您可以使用它们的通用 JsonArray
和 JsonObject
类来遍历您的 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/