将JSONobject值提取到动态生成的JSONobject内部的变量中 [英] Fetch the JSONobject value to a variable which is inside the dynamically generated JSONobject

查看:298
本文介绍了将JSONobject值提取到动态生成的JSONobject内部的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在下面的JSON响应中动态获取其中包含其他对象的JSON对象之一.尝试了此处提供的一些解决方案,但每次获取"null"都无法获取值.

We have below JSON response which has dynamically getting one of the JSONobject which has other objects inside. Tried some of the solutions provided here, but unable to get the values, every time getting 'null'.

{
  "Result": {
    "12987654": {//this value 1298.. is dynamically getting generated at every response.
      "Tests1": {
        "test1": -0.85,
        "test2": 0.016,
        "tests3": "FAIL"
      },
      "Tests2": {
        "test21": "PASS",
        "test22": "PASS",
        "test23": "FAIL"
      }
    }
  }
}

现在尝试动态获取(1298 ..)生成对象内部的值,例如Tests2.teset21. 如果尝试

Now Trying to get value of inside this dynamically (1298..) generating object, like Tests2.teset21. If tried as

JSONPath js.get("Results.1298.Tests1.test1")//able to get the value. however here 1298 is hardcoded and this value changes in the next run.

如果按以下方式尝试,则将值获取为空.

If tried as below, getting value as null.

import com.google.gson.JsonObject;

JsonObject jsonObjectResponse = (JsonObject) new JsonParser().parse(responseInString);
JsonObject Result = jsonObjectResponse.get("loanResult").getAsJsonObject();
SysOut(Result)//gives null

或者,尝试以下操作也会给出空值

OR, trying below also gives null

JsonElement jelement = new JsonParser().parse(responseInString);
         JsonObject  ResultObj = jelement.getAsJsonObject();
         System.out.println("ResultObj  value is: " + loanResultObj.get("tests21"));

请指导如何在动态生成Jsonobject的内部获取价值.

Please guide how to get value inside of dynamically generating Jsonobject.

推荐答案

最后,经过多次尝试,可以理解使用Gson来获取值.对于我的问题,动态来自请求的ID.使用以下代码可以解决问题:

Finally after many attempts, could understand using Gson to get the value. For my issue, the id which dynamic goes from Request. With below code could solve issue:

Gson gsonResp = new Gson();
        String responseInString = response.asString();
        JsonObject jsonObjectNewResponse = gsonResp.fromJson(responseInString, JsonObject.class);
String test12 = jsonObjectNewResponse.getAsJsonObject("Result").getAsJsonObject(<dynamicID which is been extracted from Req in the form of String>).            getAsJsonObject("test1").get("test12").getAsString();

这篇关于将JSONobject值提取到动态生成的JSONobject内部的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆