Skip to content

Instantly share code, notes, and snippets.

@stibi
Created December 3, 2012 09:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stibi/4193797 to your computer and use it in GitHub Desktop.
Save stibi/4193797 to your computer and use it in GitHub Desktop.
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;
}
}
@JsonRootName("myRootName")
public class FooList {
public List<FooEntity> fooList;
public FooList() {
this.fooList = new ArrayList<FooEntity>();
}
public void add(FooEntity fooEntity) {
this.fooList.add(fooEntity);
}
@JsonValue
public List<FooEntity> getFooList() {
return fooList;
}
public void setFooList(List<FooEntity> fooList) {
this.fooList = fooList;
}
}
public class WrappingTest {
@Test
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();
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
StringWriter stringWriter = new StringWriter();
final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(stringWriter);
mapper.writeValue(jsonGenerator, fooList);
System.out.println(stringWriter.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment