简体   繁体   中英

Java - Deserialize using getters/setters instead of reflection

I have a pojo that populates a hidden variable when its setter methods are invoked.

My pojo is almost identical to: Gson POJO mapping loses custom field value

I am using jackson 1.9.6 in my JAX-RS project. When a REST call is made, it consumes JSON and automagically converts it to an instance of the pojo. I believe jackson is using reflection to do this. The reason this is bad for me is because reflection bypasses the setter methods and my hidden variable is never populated.

How do I tell jackson to avoid reflection and to specifically call the getter/setter methods? Do I have to tag each pojo with @JsonDeserialize? If so, how would I write a generic Deserializer (aka MyDeserializer extends JsonDeserializer<T> ) to handle different pojos? Is there a better way that I'm not thinking of?

Note: In test cases (outside of REST) I have had success using ObjectMapper.readValue(json,class) , but I'm not sure how to migrate that code into a JsonDeserializer.

I had a problem similar to this: I was using Retrofit, and Jackson, and deserializing the JSON key always ignored my annotated setter and used reflection on the private fields and never set anything. It turns out that the gem of information I needed (RTFM), was that Retrofit uses GSON by default and that is GSON behaviour. Jackson wasn't being used to deserialize.

So you need to write a Retrofit converter that uses Jackson. An example of that can be found here: http://kdubblabs.com/java/retrofit-by-square/retrofit-using-jackson-json-conversion/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM