stibi
stibi

Reputation: 1039

How to modify root element of JSON array serialized with Jackson

see following code. I need to serialize a list of data into JSON array:

FooEntity.java:

public class FooEntity {

String foo;
String bar;

public String getFoo() {
    return foo;
}

public void setFoo(String foo) {
    this.foo = foo;
}

public String getBar() {
    return bar;
}

public void setBar(String bar) {
    this.bar = bar;
}
}

FooList.java:

public class FooList {
public List<FooEntity> fooList;

public FooList() {
    this.fooList = new ArrayList<FooEntity>();
}

public void add(FooEntity fooEntity) {
    this.fooList.add(fooEntity);
}

public List<FooEntity> getFooList() {
    return fooList;
}

public void setFooList(List<FooEntity> fooList) {
    this.fooList = fooList;
}
}

Here I create the list of FooEntities and serialize it into JSON:

public void fooListToJson() throws IOException {
    FooList fooList = new FooList();

    FooEntity fooEntity1 = new FooEntity();
    fooEntity1.setBar("fooEntity1 bar value");
    fooEntity1.setFoo("fooEntity1 foo value");

    FooEntity fooEntity2 = new FooEntity();
    fooEntity2.setBar("fooEntity2 bar value");
    fooEntity2.setFoo("fooEntity2 foo value");

    fooList.add(fooEntity1);
    fooList.add(fooEntity2);

    ObjectMapper mapper = new ObjectMapper();
    StringWriter stringWriter = new StringWriter();
    final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(stringWriter);

    mapper.writeValue(jsonGenerator, fooList);

    System.out.println(stringWriter.toString());

So the output is followting:

{"fooList":[{"foo":"fooEntity1 foo value","bar":"fooEntity1 bar value"},{"foo":"fooEntity2 foo value","bar":"fooEntity2 bar value"}]}

That's all is correct, I have here only one need. I need to change the "root" element of the list. Right now there is "fooList" as root element - I need to change it.

I've found few threads and posts to this topic, but nothing was working for me exactly as I want. The solution have to keep the possibility to deserialize the JSON back to corresponding java classes.

Upvotes: 2

Views: 3728

Answers (1)

hd1
hd1

Reputation: 34677

Does @JsonRootName provide what you need?

Upvotes: 1

Related Questions