Given the following POJO ..
public class City {
private String title;
private List<Person> people;
}
...
public class Person {
private String name;
private int age;
}
I would like to allow Jackson to serialize class instances in the following JSON example:
{
"title" : "New York",
"personName_1" : "Jane Doe",
"personAge_1" : 42,
"personName_2" : "John Doe",
"personAge_2" : 23
}
The JSON format is determined by an external API, which I cannot change.
I already found that I can annotate a list box using a special serializer, for example:
@JsonSerialize(using = PeopleSerializer.class)
private List<Person> people;
... and here is the basic implementation I tried:
public class PeopleSerializer extends JsonSerializer<List<Person>> {
private static final int START_INDEX = 1;
@Override
public void serialize(List<Person> people,
JsonGenerator generator,
SerializerProvider provider) throws IOException {
for (int i = 0; i < people.size(); ++i) {
Person person = people.get(i);
int index = i + START_INDEX;
serialize(person, index, generator);
}
}
private void serialize(Person person, int index, JsonGenerator generator) throws IOException {
generator.writeStringField(getIndexedFieldName("personName", index),
person.getName());
generator.writeNumberField(getIndexedFieldName("personAge", index),
person.getAge());
}
private String getIndexedFieldName(String fieldName, int index) {
return fieldName + "_" + index;
}
}
However, this does not work with:
JsonGenerationException: Can not write a field name, expecting a value
I also studied using the Jackson Converter interface , but this is not suitable for deploying nested list objects.
I also know @JsonUnwrapped, but it is not intended for use with lists.
Related Posts
()