首页 > 解决方案 > Spring RestTemplate,我可以从获得的 JSON 响应中检索特定的单个字段,避免声明模型类吗?

问题描述

我正在开发一个 Spring Boot 项目,以这种方式对外部 API 执行 REST 调用:

@Override
public List<NotaryDistrictDetails> getNotaryDistrictDetailsByDistictId(String districtId) throws URISyntaxException {
    
    String completeURL =  this.wpPortalBasicNotaryDistrictPostBaseURL.replace("{districtId}", districtId);
    System.out.println("completeURL: " + completeURL);
    
    URI uri = new URI(completeURL);
    System.out.println(uri);
    
    ResponseEntity<String> forEntity = restTemplate.getForEntity(uri, String.class);
    
    System.out.println(forEntity.getStatusCodeValue());
    System.out.println(forEntity.getBody());
    
    
    return null;
}

目前 println 输出是这样的(这是正确的):

200
[{"post_type":"notary-district","ID":38804,"wpcf-idnotary-district":"XXX","post_title":"AA"}]

我知道要检索特定字段,我可以创建一个包含这些字段的模型对象,然后执行以下操作:

ResponseEntity<String> forEntity = restTemplate.getForEntity(uri, MyModelClass.class);

然后检索我的所有属性。

但在这种情况下,我只需要从前一个 JSON 响应中检索单个特定字段的值,即ID字段,这个"ID":38804。这是因为我必须使用这个检索到的值来执行第二个外部 API 调用,并将这个 ID 作为参数传递。

我的问题是:是否存在一种直接检索单个字段值(在本例中为 ID 字段值)的方法,避免为此响应创建模型类?还是我要创建一个模型类并检索与我的响应相关的整个对象,然后从这里检索 ID 字段?

标签: javaspringspring-bootresttemplate

解决方案


正如我在原始帖子的评论中所建议的那样,我使用JsonNode Jackson 对象解决了我的解决方案:

@Override
public List<NotaryDistrictDetails> getNotaryDistrictDetailsByDistictId(String districtId) throws URISyntaxException, JsonMappingException, JsonProcessingException {
    
    String completeURL =  this.wpPortalBasicNotaryDistrictPostBaseURL.replace("{districtId}", districtId);
    System.out.println("completeURL: " + completeURL);
    
    URI uri = new URI(completeURL);
    System.out.println(uri);
    
    ResponseEntity<String> forEntity = restTemplate.getForEntity(uri, String.class);
    
    
    ObjectMapper objectMapper = new ObjectMapper();

    JsonNode jsonNode = objectMapper.readTree(forEntity.getBody());
    
    System.out.println("jsonNode: " + jsonNode.get(0).toPrettyString());
        
    System.out.println("ID: " + jsonNode.get(0).get("ID"));

    
    return null;
}

推荐阅读