开发者

Spring Android - Deserializing JSON objects causing issues when there is inheritance

开发者 https://www.devze.com 2023-02-24 21:11 出处:网络
I am facing an issue with Deserializing a POJO object. Following is the structure of the POJO objects on the Service side.

I am facing an issue with Deserializing a POJO object.

Following is the structure of the POJO objects on the Service side.

Class Ball{
    int field1;
    int field2;

}

Class BaseBall extends Ball
{
    int field3;
    int field4;
}

Class BallList{
    List<Ball> balls;
}

Even on the Android Client side, i have a similar structure for the POJO objects.

Code for Android Client:

RestTemplate restTemplate = new RestTemplate();

List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(new MediaType("application","json"));

HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);

HttpEntity<String> entity = new HttpEnti开发者_StackOverflow中文版ty<String>(headers);

ResponseEntity<BallList> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, BallList.class);

if(response.getStatusCode() == HttpStatus.OK)
{
    result += "OK";
}

04-13 18:17:46.127: ERROR/AndroidRuntime(4359): Caused by: org.springframework.web.client.ResourceAccessExcep tion: I/O error: Unrecognized field "filed3" (Class com.xx.yy.model.Ball), not marked as ignorable

On the service side, i am providing the baseball list as a response. Can anyone point me to a solution please.


This is not really Android problem. The system looks at your stuff from Ball level and hence you get Unrecognized field "field3" exception. Also I would declare acceptibleMediaType as ArrayList since List is not serializable.

I would try to create and send ArrayList<BaseBall> just to see if it works and then go from there


Spring Recently released (3.2.0.RELEASE) and they added MappingJackson2HttpMessageConverter which solved a similar problem I had. MappingJackson2HttpMessageConverter uses Jackson 2 for deserialization while MappingJacksonHttpMessageConverter uses pre-2.0 Jackson. Try adding following converter to your RestTemplate and give it a shot.

MappingJackson2HttpMessageConverter map = new MappingJackson2HttpMessageConverter();
messageConverters.add(map);
restTemplate.setMessageConverters(messageConverters);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号