Forcing Jackson to deserialize to specific primiti

2020-02-05 07:08发布

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?

7条回答
The star\"
2楼-- · 2020-02-05 07:31

I've used something like the below to work around this problem.

@JsonIgnoreProperties(ignoreUnknown = true)
public class Message {
    public Long ID;

    @JsonCreator
    private Message(Map<String,Object> properties) {
        try {
            this.ID = (Long) properties.get("id");
        } catch (ClassCastException e) {
            this.ID = ((Integer) properties.get("id")).longValue();
        }
    }
}
查看更多
登录 后发表回答