Option 1 : Just annotate the getter method of the Foo1.class
@JsonProperty("comments")
public List getComments() {
List list = new ArrayList();
list.add(comments);
return list;
}
@JsonProperty("attachments")
public List getAttachments() {
List list = new ArrayList();
list.add(attachments);
return list;
}
Foo1 foo1 = new Foo1(Long.valueOf(1),"a","aaa",true,"abc","def");
System.out.println(new ObjectMapper().writeValueAsString(foo1));
Foo2 foo2 = new ObjectMapper().convertValue(foo1, Foo2.class);
System.out.println(new ObjectMapper().writeValueAsString(foo2));
Option 2 : use jackson-custom-serialization
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Foo1.class,new ListSerializer());
mapper.registerModule(simpleModule);
public class ListSerializer extends StdSerializer<Foo1> {
public ListSerializer() {
this(null);
}
protected ListSerializer(Class<Blah.Foo1> t) {
super(t);
}
public void serialize(Blah.Foo1 foo1, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
List list = new ArrayList();
list.add(foo1.getComments());
List list1 = new ArrayList();
list1.add(foo1.getAttachments());
jsonGenerator.writeObjectField("id",foo1.getId());
jsonGenerator.writeObjectField("code",foo1.getCode());
jsonGenerator.writeObjectField("name",foo1.getName());
jsonGenerator.writeObjectField("rState",foo1.getrState());
jsonGenerator.writeObjectField("comments",list);
jsonGenerator.writeObjectField("attachments",list1);
jsonGenerator.writeEndObject();
}
}
Foo1 foo1 = new Foo1(Long.valueOf(1),"a","aaa",true,"abc","def");
System.out.println(mapper.writeValueAsString(foo1));
Foo2 foo2 = mapper.convertValue(foo1, Foo2.class);
System.out.println(new ObjectMapper().writeValueAsString(foo2));