Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Databind ObjectMapper convertValue with custom mapping implementaion

Foo1

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

}

Foo2

public class Foo2{

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

}

convert value

new ObjectMapper().convertValue(foo1, Foo2.class);

is it possible, when I call convert value, json String automatically convert to list ?

like image 309
Shahid Ghafoor Avatar asked Nov 06 '22 11:11

Shahid Ghafoor


1 Answers

I would recommend going with a Deserializer as Foo1 might actually be serialized elsewhere and we might only have it's serialized data to convert. And that is what is our goal here.

Create a SimpleModule that deserializes List type

public class ListDeserializer extends StdDeserializer<List> {

    public ListDeserializer() {
        super(List.class);
    }

    @Override
    public List deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException {
        if (p.getCurrentName().equals("result") || p.getCurrentName().equals("attachments")) {
            JsonNode node = p.getCodec().readTree(p);
            return new ObjectMapper().readValue(node.asText(), List.class);
        }
        return null;
    }
}

The above deserializer only recognizes result and attachments and ignores the rest. So this is a very specific deserializer for List in Foo2 class.

My test Foo1 and Foo2 are as follows

public class Foo1 {

    String result = "[\"abcd\", \"xyz\"]";

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
}

public class Foo2 {

    List result;

    public List getResult() {
        return result;
    }

    public void setResult(List result) {
        this.result = result;
    }
}

I tested the above code as follows

// Module to help deserialize List objects
SimpleModule listModule = new SimpleModule();
listModule.addDeserializer(List.class, new ListDeserializer());

ObjectMapper objectMapper = new ObjectMapper().registerModules(listModule);
Foo2 foo2 = objectMapper.convertValue(new Foo1(), Foo2.class);
System.out.println(foo2.getResult());

And the output is

[abcd, xyz]
like image 172
Sunil Dabburi Avatar answered Nov 14 '22 23:11

Sunil Dabburi