如何使用resttemplate.exchange()从json映射到Java对象

时间:2018-07-03 20:55:41

标签: json spring mapping resttemplate jackson-databind

我正在尝试使用spring resttemplate使用rest服务。因为此服务需要基本身份验证,所以我不使用doGetForObject()而是exchange()。我使用jackson-databind 2 lib和spring 4.3。我尝试了两种方法来获取响应。

1st way
    ResponseEntity<ServiceRegistryResponse> bmResponse =  restTemplate.exchange(url,HttpMethod.GET, entityRequest, ServiceRegistryResponse.class);

2nd way 
    ResponseEntity<String> bmResponse =  restTemplate.exchange(url,HttpMethod.GET, entityRequest, String.class);
    ObjectMapper mapper = new ObjectMapper();
    ServiceRegistryResponse obj = mapper.readValue(bmResponse.getBody(), ServiceRegistryResponse.class);

在调试模式下,我可以看到我从服务中获取了json字符串。但是json映射无法按我预期的方式工作:ServiceRegistryResponse.serviceRegistryData始终为null。

以下是这些类:

@JsonIgnoreProperties(ignoreUnknown=true)
public class ServiceRegistryResponse  implements Serializable{
   private static final long serialVersionUID = 1L;
   @JsonProperty("serviceRegistryData") 
   private List<ServiceRegistryData> serviceRegistryData;
   .....
}

@JsonIgnoreProperties(ignoreUnknown=true)
public class ServiceRegistryData implements Serializable {
    private static final long serialVersionUID = 1L;
    private String productName;
    ....
} 

这是json响应:

<200 OK,{"serviceRegistryResponse":{"serviceRegistryData":[{"productName":"AAAAAAA",.....},{...},{...}]}}>

0 个答案:

没有答案