[英]Jackson: serialize only a given instance variable of a given class
Note that by serialization, I mean serializing to JSON (either a JsonNode, or the String representation of it). 请注意,通过序列化,我的意思是序列化为JSON(JsonNode或它的String表示形式)。
This is Jackson 2.2.3. 这是杰克逊2.2.3。 My class looks like this:
我的课看起来像这样:
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);
}
}
I already know how to serialize all Bar
instances (tested). 我已经知道如何序列化所有
Bar
实例(已测试)。 Now I need to be able to serialize a Foo
instance. 现在,我需要能够序列化
Foo
实例。
The only thing I have been able to do at the moment is to "decorate" l
with a @JsonSerialize
annotation but this gives: 目前,我唯一能做的就是用
@JsonSerialize
注释“装饰” l
,但这给出了:
{ "l": [ { "serializedForm": "of bar1"}, { "serializedForm": "of bar2"} ] }
And I want: 而且我要:
[ { "serializedForm": "of bar1"}, { "serializedForm": "of bar2"} ]
How do I achieve that? 我该如何实现? Note: I can use jackson-annotations
注意:我可以使用杰克逊注释
Note also that I can perfectly deserialize the second form to a valid, functional, Foo
instance. 还要注意,我可以完美地将第二种形式反序列化为有效的,功能齐全的
Foo
实例。
This 这个
{ "l": [ { "serializedForm": "of bar1"}, { serializedForm": "of bar2"} ] }
is the correct serialization of 是正确的序列化
public final class Foo
{
// the one and only instance variable
private final List<Bar> l;
}
The JSON is a JSON object that contains a JSON array named l
that contains two other JSON objects. JSON是一个JSON对象,其中包含一个名为
l
的JSON数组,该数组包含另外两个JSON对象。 From a Java perspective, this is also true. 从Java的角度来看,这也是正确的。 You have aa
Foo
object, which contains a List
(corresponding to the JSON array) named l
, that contains x Bar
objects. 您有一个
Foo
对象,其中包含一个名为l
的List
(对应于JSON数组),该列表包含x个Bar
对象。
If you really want that JSON, annotate your field's getter with @JsonValue
. 如果您确实需要该JSON,请使用
@JsonValue
注释字段的getter。 Read the javadoc carefully, because there are restrictions. 由于存在限制,请仔细阅读javadoc。 For example
例如
At most one method of a Class can be annotated with this annotation;
该注释最多可以注释一个Class方法。 if more than one is found, an exception may be thrown.
如果发现多个,则可能引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.