2

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.

1 Answer 1

1

Does @JsonRootName provide what you need?

Sign up to request clarification or add additional context in comments.

2 Comments

Hi! Yes, it works. I've gave it a try before, but it needs few more things - enabled WRAP_ROOT_VALUE for ObjectMapper and then also @JsonValue annotation for the List containing data, to flatten the serialized JSON (stackoverflow.com/questions/13386930/…). See this gist with complete solution: gist.github.com/4193797
FYI link is broken

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.