Jackson Databind ObjectMapper ConvertValue 与自定义映射实现

Sha*_*oor 8 java jackson jackson-databind

富1

public class Foo1{

private Long id;
private String code;
private String name;
private Boolean rState;
private String comments;     // Contain json data
private String attachments;  // Contain json data

}
Run Code Online (Sandbox Code Playgroud)

富2

public class Foo2{

private Long id;
private String code;
private String name;
private Boolean rState;
private List comments;
private List attachments;

}
Run Code Online (Sandbox Code Playgroud)

转换值

new ObjectMapper().convertValue(foo1, Foo2.class);
Run Code Online (Sandbox Code Playgroud)

当我调用转换值时,json字符串是否可以自动转换为列表?

das*_*sum 0

选项1:只需注释Foo1.class的getter方法

@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));
Run Code Online (Sandbox Code Playgroud)

选项 2:使用 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));
Run Code Online (Sandbox Code Playgroud)