gson Jackson:仅序列化标记字段

ne5o7dgx  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(128)

我正在尝试做一些在gson中很容易的事情。自从我切换到Jackson作为序列化器后,我不知道如何实现:
我只想序列化已经被Annotation标记的字段。GSON代码应该是:

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

字符串
结果应该是(JSON)

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


(错误可能会被忽略-源代码只是为了演示)
那么Jackson对gson的@Exposenew GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();的对应是什么呢?

li9yvcax

li9yvcax1#

如果你只想要一个特定的类型,你也可以使用注解:

import com.fasterxml.jackson.annotation.JsonAutoDetect;

@JsonAutoDetect(
    fieldVisibility = JsonAutoDetect.Visibility.NONE,
    setterVisibility = JsonAutoDetect.Visibility.NONE,
    getterVisibility = JsonAutoDetect.Visibility.NONE,
    isGetterVisibility = JsonAutoDetect.Visibility.NONE,
    creatorVisibility = JsonAutoDetect.Visibility.NONE
)
public class Foo  {
    @JsonProperty
    public String sometext="Hello World";
    @JsonProperty
    public int somenumber=30;
    // noop won't get serialized
    public float noop= 1.0f;
}

字符串

ig9co6j1

ig9co6j12#

new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();的对应部分是初始化ObjectMapper,如下所示:

...
ObjectMapper objectMapper = new ObjectMapper();        
objectMapper.disable(MapperFeature.AUTO_DETECT_CREATORS,
            MapperFeature.AUTO_DETECT_FIELDS,
            MapperFeature.AUTO_DETECT_GETTERS,
            MapperFeature.AUTO_DETECT_IS_GETTERS);
...

字符串
那么@Expose的对应物是@JsonProperty。使用上面的示例bean:

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


this answer是一个非常类似的问题。

oaxa6hgo

oaxa6hgo3#

似乎有一种方法可以配置ObjectMapper忽略所有未注解的字段。“

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

nbewdwxp

nbewdwxp4#

在Jackson中,你做了相反的事情。用@JsonIgnore注解你不想要的字段。
标记注解,指示基于内省的序列化和非序列化功能将忽略注解的方法或字段。也就是说,不应将其视为“getter”、“setter”或“creator”。

相关问题