Java 如何在序列化对象时让 Jackson 忽略 get() 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/23477002/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make Hymanson ignore a get() method when serializing an object
提问by NoUserFound
I have this code in a class named Project:
我在一个名为的类中有此代码Project:
@Transient
public List<Release> getAllReleases() {
    List<Release> releases = new ArrayList<Release>();
    ...
    return releases;
}
When a project object is serialized the getAllReleases()method is called, and an allReleasesfield is added to the serialized object.
当一个项目对象被序列化时,该getAllReleases()方法被调用,并且一个allReleases字段被添加到序列化的对象中。
If I add @JsonIgnorebefore the method I get the same result. So I wonder how can I implement a getFoo()method which is ignored by Hymanson when serializing the object.
如果我@JsonIgnore在方法之前添加,我会得到相同的结果。所以我想知道如何实现一个getFoo()在序列化对象时被Hyman逊忽略的方法。
Alternatively I could do:
或者我可以这样做:
static public List<Release> getAllReleases(Project proj) {
    List<Release> releases = new ArrayList<Release>();
    ...
    return releases;
}
but the solution looks a bit ugly, and I'm pretty sure there must be some simpler mechanism provided by Hymanson.
但解决方案看起来有点难看,我很确定Hyman逊必须提供一些更简单的机制。
Am I missing something? TIA
我错过了什么吗?TIA
回答by Excelsior
You need to implement a JSon serializer which does nothing and then set it using @JSonSerialize(using = EmptySerializer.class).
您需要实现一个什么都不做的 JSon 序列化器,然后使用 @JSonSerialize(使用 = EmptySerializer.class)设置它。
Click on the refrence for further example.
单击参考以获取更多示例。
Reference: Hymanson: how to prevent field serialization
回答by Alexey Gavrilov
If you mark the getter method with the @JsonIgnoreannotation it should not be serialized. Here is an example:
如果使用@JsonIgnore注释标记 getter 方法,则不应对其进行序列化。下面是一个例子:
public class HymansonIgnore {
    public static class Release {
        public final String version;
        public Release(String version) {
            this.version = version;
        }
    }
    public static class Project {
        public final String name;
        public Project(String name) {
            this.name = name;
        }
        @JsonIgnore
        public List<Release> getAllReleases() {
            return Arrays.asList(new Release("r1"), new Release("r2"));
        }
    }
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Project("test")));
    }
}
Output:
输出:
{
  "name" : "test"
}

