在jackson序列化的所有对象中包含类名 [英] include class name in all objects serialized by jackson

查看:2474
本文介绍了在jackson序列化的所有对象中包含类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在所有序列化对象中包含类名?例如。将_class:'MyClass'添加到输出值。是否有一些全球性的背景?我不想在pojo类中添加任何注释。

How to include class name in all serialized objects? E.g. adding "_class: 'MyClass'" to output value. Is there some global setting for that? I don't want to add any annotation to pojo classes.

我正在使用spring4 webmvc @ResponseBody(仅限json格式)。

I'm using it with spring4 webmvc @ResponseBody (only json format).

推荐答案

您需要使用 @JsonTypeInfo 注释注释您的类型,配置类型信息应该如何序列化。请参阅此页面以供参考。

You need to annotated your type with the @JsonTypeInfo annotation and configure how the type information should be serialized. Refer this page for reference.

示例:

public class JacksonClassInfo {
    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "__class")
    public static class Bean {
        public final String field;

        @JsonCreator
        public Bean(@JsonProperty("field") String field) {
            this.field = field;
        }

        @Override
        public String toString() {
            return "Bean{" +
                    "field='" + field + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        Bean bean = new Bean("value");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean);
        System.out.println(json);
        System.out.println(mapper.readValue(json, Bean.class));
    }
}

输出:

{
  "__class" : "stackoverflow.JacksonClassInfo$Bean",
  "field" : "value"
}
Bean{field='value'}

这篇关于在jackson序列化的所有对象中包含类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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