【问题标题】:How to retrieve the particular object field in Java?如何在 Java 中检索特定的对象字段?
【发布时间】:2021-11-16 06:29:26
【问题描述】:

当我得到结果时,我有这样的休息调用,我得到的是这样的字符串格式,

   public String getData(String value) throws ParseException {
                final String url = "https://v1/supplier/suggest/{value}";
                Map<String, String> params = new HashMap<String, String>();
                params.put("value", value);
                HttpEntity<?> httpEntity = new HttpEntity<>(this.getAuthHeaders());
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<String> tpBody = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, params);
    JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject) parser.parse(tpBody.getBody());
        JSONArray jsonArray = (JSONArray) json.get("data");
        if (jsonArray.isEmpty()) {
            System.out.println("No Data in JsonArray");
        } else {
            Object object = jsonArray.get(0);
            System.out.println(object.toString());
        }
    }
        
            }

回应:-

{"value":"DRAGON","datas":9.5}

现在从这个字符串中我只想要数据字段值,比如假设只有 9.5

感谢任何形式的帮助。

【问题讨论】:

  • 你需要解析 JSON。您可以使用javax.json 库。
  • 您需要解析消息并从该对象中获取所需的字段。我建议查看 JasonPath 库,这将使您的工作变得轻松。它具有解析 Json 字符串并从中获取所需字段的能力。

标签: java spring spring-boot


【解决方案1】:
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    JSONObject obj = new JSONObject(json);
    JSONArray arr = obj.getJSONArray("data");
    for (int i = 0; i < arr.length(); i++) {
        String datas = arr.getJSONObject(i).getString("datas");
        System.out.println(datas);
    }

【讨论】:

  • 根据您的要求,您可以解析(其他注释中的示例代码)正文或直接将其转换为 DTO 对象并获取所需的值(参考:baeldung.com/rest-template#2-retrieving-pojo-instead-of-json)。建议您使用 WebClient,因为在未来的版本中,RestTemplate 将被弃用。
【解决方案2】:

您得到的 JSON 响应只不过是一个 Map。因此,我建议使用 Jackson 库将 json 转换为 Map,然后获取键“数据”的值 - 如下所示:

   ObjectMapper mapper = new ObjectMapper();
   Map<String, Object> map = mapper.readValue(object.toString(),Map.class);
   Double datasValue = (Double) map.get("datas");

Jackson 的依赖是:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>

【讨论】:

    猜你喜欢
    • 2019-12-15
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2017-06-15
    • 1970-01-01
    • 2022-07-18
    相关资源
    最近更新 更多