我正在使用 RestTemplate.getForObject()
检索包含几个对象和数组的 json,我只想将此 json 中的其中一个对象转换为 POJO,我不想不关心这个 json 中的其他对象。
解决这个问题的正确方法是什么?
编辑:
接受答案的另一种方法,我们可以使用 jackson ObjectMapper
@Autowired
private ObjectMapper jacksonObjectMapper;
然后
LinkedHashMap obj1 = restTemplate.getForObject(uri, LinkedHashMap.class, params);
LinkedHashMap obj2 = (LinkedHashMap)test.get("flightStatuses");
Flight flight = jacksonObjectMapper.convertValue(obj2, Flight.class);
您明白了,只需从 json 结构中获取通用数据类型,然后使用 ObjectMapper
将其转换为您需要的类即可。
最佳答案
一种解决方案是创建一个包装类,其中包含要反序列化的 POJO 并使用 @JsonIgnoreProperties
忽略所有其他属性。然后,您将检索包装器对象并从中获取 POJO。
@JsonIgnoreProperties(ignoreUnknown=true)
public class Wrapper {
private MyPojo myPojo;
}
MyPojo myPojo = restTemplate.getForObject("url", Wrapper.class).getMyPojo();
关于spring - RestTemplate getForObject 到 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33371806/