fge
fge

Reputation: 121790

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).

This is Jackson 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). Now I need to be able to serialize a Foo instance.

The only thing I have been able to do at the moment is to "decorate" l with a @JsonSerialize annotation but this gives:

{ "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.

Upvotes: 1

Views: 904

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280112

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. From a Java perspective, this is also true. You have a a Foo object, which contains a List (corresponding to the JSON array) named l, that contains x Bar objects.

If you really want that JSON, annotate your field's getter with @JsonValue. Read the javadoc carefully, because there are restrictions. For example

At most one method of a Class can be annotated with this annotation; if more than one is found, an exception may be thrown.

Upvotes: 1

Related Questions