杰克逊:只序列化标记的字段 [英] Jackson: Serialize only marked fields

查看:314
本文介绍了杰克逊:只序列化标记的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一些在gson中很容易的事情。自从我切换到串行器的杰克逊,我无法弄清楚如何实现这一点:



我想只序列化由注释标记的字段。 GSON代码是:

  class Foo {
@Expose
public String sometext =Hello World ;
@Expose
public int somenumber = 30;
public float noop = 1.0;
...
}

这会导致(JSON) p>

  {
Foo:{
sometext:'Hello World',
somenumber:30




$ b(语法错误可能会被忽略 - 源代码仅用于演示)


那么杰克逊对应的gson的 @Expose 新的GsonBuilder()。excludeFieldsWithoutExposeAnnotation ().create();

解决方案

似乎有一种方法可以配置 ObjectMapper 来忽略所有

  ObjectMapper mapper = new ObjectMapper(); 
mapper.setVisibilityChecker(getSerializationConfig()。getDefaultVisibilityChecker()
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE)$ b $ withFieldVisibility(JsonAutoDetect.Visibility.NONE)
.withGetterVisibility(JsonAutoDetect。 Visibility.NONE)
.withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE));

来源


I am trying to do something which was quite easy in gson. Since I switched to Jackson as serializer, I couldn't figure out how to implement this:

I want to serialize only fields that have been marked by an Annotation. GSON code would be:

class Foo {
    @Expose
    public String sometext="Hello World";
    @Expose
    public int somenumber=30;
    public float noop=1.0;
    ...
 }

which should result in (JSON)

 {
    Foo: {
        sometext:'Hello World',
        somenumber: 30
    }
 }

(Syntax errors may be ignored - source is just for demonstration)

So what's the Jackson counterpart for gson's @Expose and new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();?

解决方案

There seems to be a way to configure ObjectMapper to ignore all non annotated fields.

ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(getSerializationConfig().getDefaultVisibilityChecker()
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
.withFieldVisibility(JsonAutoDetect.Visibility.NONE)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE));

Source

这篇关于杰克逊:只序列化标记的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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