public
Created

  • Download Gist
FooEntity.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
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
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
@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;
}
}
WrappingTest.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
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());
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.