强制 Jackson 反序列化为特定的原始类型 [英] Forcing Jackson to deserialize to specific primitive type

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

问题描述

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

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);

然后反序列化

mapper.readValue(destination, Node.class);

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

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.

我如何强制"Jackson 将数字非十进制值反序列化为 Long 而不是 Integer?

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

推荐答案

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

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").

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

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