Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing Jackson to deserialize to specific primitive type

Tags:

I am serializing and deserializing following domain object to JSON using Jackson 1.8.3

public class Node {     private String key;     private Object value;     private List<Node> children = new ArrayList<Node>();     /* getters and setters omitted for brevity */ } 

Object is then serialized and deserialized using following code

ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(destination, rootNode); 

And then later deserialized with

mapper.readValue(destination, Node.class); 

The original values of the object are either Strings, Doubles, Longs or Booleans. However, during serialization and deserialization Jackson transforms Long values (such as 4) to Integers.

How can I "force" Jackson to deserialize numeric non-decimal values to Long instead of Integer?

like image 317
Peders Avatar asked Sep 06 '11 08:09

Peders


People also ask

How does Jackson deserialization work?

Jackson uses default (no argument) constructor to create object and then sets value using setters. so you only need @NoArgsConstructor and @Setter.

How do I add custom deserializer to Jackson?

To create a custom deserializer, we need to create a class extending StdDeserializer and then override its deserialize() method. We can use custom deserializer either by registering with ObjectMapper or annotating class with @JsonDeserialize . Now find the JSON used in our demo.

Does Jackson use Java serialization?

Note that Jackson does not use java.


1 Answers

There is a new feature in Jackson 2.6 specifically for this case:

configure the ObjectMapper to use DeserializationFeature.USE_LONG_FOR_INTS

see https://github.com/FasterXML/jackson-databind/issues/504

cowtowncoder pushed a commit that closed this issue on May 19, 2015 Fix #504 and #797

like image 140
Fabian Lange Avatar answered Oct 26 '22 15:10

Fabian Lange