Paviel26
Paviel26

Reputation: 11

Jackson Serialization to Array

I have the following class:

class People
{
    private List<String> people = new ArrayList<>();

    public People()
    {
        people.add("Jhon");
        people.add("Rose");
    }
}

it is serialized using jackson to {"people":["Jhon","Rose"]}

I would like to serialize to ["Jhon","Rose"] without custom serializers.

any suggestion?

any help will be appreciated!

Upvotes: 1

Views: 292

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22244

The simplest way would be to get the field and serialize that instead of the wrapper object:

People people = new People();
String json = mapper.writeValueAsString(people.getPeople());

If that's not an option, a Converter may be simpler than a custom serializer:

class PeopleToList extends StdConverter<People, List<String>> {
    @Override public List<String> convert(People people) {
        return people.getPeople();
    }
}

and specify to use that:

@JsonSerialize(converter = PeopleToList.class)
class People {

Upvotes: 2

Related Questions