【问题标题】:Fetch the JSONobject value to a variable which is inside the dynamically generated JSONobject将 JSONobject 值获取到动态生成的 JSONobject 中的变量
【发布时间】:2020-08-28 18:35:27
【问题描述】:

我们有下面的 JSON 响应,它动态获取其中一个 JSONobject,其中包含其他对象。尝试了此处提供的一些解决方案,但无法获取值,每次都获得“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。 如果尝试为

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.

如果尝试如下,获取值为 null。

import com.google.gson.JsonObject;

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

或者,下面的尝试也给出了 null

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

请指导如何在动态生成的 Jsonobject 中获取值。

【问题讨论】:

    标签: gson pojo jsonpath jsonparser rest-assured-jsonpath


    【解决方案1】:

    经过多次尝试,终于可以理解使用Gson获取值了。对于我的问题,动态来自 Request 的 id。使用以下代码可以解决问题:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 2016-03-16
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多