迫使杰克逊反序列化为特定的原始类型 [英] Forcing Jackson to deserialize to specific primitive type

查看:131
本文介绍了迫使杰克逊反序列化为特定的原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Jackson 1.8.3将以下域对象序列化和反序列化为JSON

  public class Node {
私有String键;
私有对象值;
private List< Node> children = new ArrayList< Node>();为简洁而省略
/ * getters和setter * /
}

对象是然后使用以下代码进行序列化和反序列化

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

然后用



$ b <$ p $反序列化p> mapper.readValue(destination,Node.class);

对象的原始值是字符串,双打,长整数或布尔值。但是,在序列化和反序列化期间,Jackson将Long值(例如4)转换为Integers。



如何强制杰克逊将数字非十进制值反序列化为Long而不是Integer?

解决方案

如果将type声明为java.lang.Object,则Jackson使用自然映射,如果值适合32,则使用Integer位。除了自定义处理程序之外,您还必须强制包含类型信息(通过在field / getter旁边添加@JsonTypeInfo;或者通过启用所谓的默认类型)。


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?

解决方案

If type is declared as java.lang.Object, Jackson uses 'natural' mapping which uses Integer if value fits in 32 bits. Aside from custom handlers you would have to force inclusion of type information (either by adding @JsonTypeInfo next to field / getter; or by enabling so-called "default typing").

这篇关于迫使杰克逊反序列化为特定的原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆