Jackson:仅序列化给定类的给定实例变量

时间:2014-02-15 23:48:12

标签: java serialization jackson

请注意,通过序列化,我的意思是序列化为JSON(JsonNode或它的String表示)。

这是杰克逊2.2.3。我的班级看起来像这样:

public final class Foo
{
    // the one and only instance variable
    private final List<Bar> l;

    // Allows deserialization with no problem at all
    @JsonCreator
    public Foo(final List<Bar> l)
    {
        this.l = ImmutableList.copyOf(l);
    }
}

我已经知道如何序列化所有Bar个实例(已测试)。现在我需要能够序列化Foo实例。

我目前唯一能做的就是装饰&#34;带有l注释的@JsonSerialize,但这会给出:

{ "l": [ { "serializedForm": "of bar1"}, { "serializedForm": "of bar2"} ] }

我想要:

[ { "serializedForm": "of bar1"}, { "serializedForm": "of bar2"} ]

我如何实现这一目标?注意:我可以使用jackson-annotations

另请注意,我可以将第二个表单完全反序列化为有效的,功能性Foo实例。

1 个答案:

答案 0 :(得分:1)

{ "l": [ { "serializedForm": "of bar1"}, { serializedForm": "of bar2"} ] }

的正确序列化
public final class Foo
{
    // the one and only instance variable
    private final List<Bar> l;
}

JSON是一个JSON对象,它包含一个名为l的JSON数组,其中包含另外两个JSON对象。从Java的角度来看,这也是事实。您有一个Foo对象,其中包含名为List的{​​{1}}(对应于JSON数组),其中包含x l个对象。

如果您真的想要JSON,请使用@JsonValue注释您的字段的getter。仔细阅读javadoc,因为有限制。例如

  

最多可以使用此注释对类的一个方法进行注释;   如果找到多个,则可能会抛出异常。