nsharma
nsharma

Reputation: 118

Map JSON to existing pojo object

I have recently joined the web services world and have started to work on create and update of hibernate entities using json inputs.

The following api converts a json input to new pojo object:

Pojo newObject=mapper.readValue(jsonInput,Pojo.class);

This work well with create apis.

Now what about update apis:

I have a big pojo and i don't want to get into long method setting each value into pojo object from json input

i want something like:

Pojo existingPojo=getFromDatabase();

existingPojo=mapper.readValue(updateJsonValues,existingPojo);

saveToDatabase(existingPojo);

So whatever attributes updateJsonValues has ,they get updated into existingPojo.

This would be great help.Thanks in advance.

Upvotes: 0

Views: 757

Answers (2)

tevemadar
tevemadar

Reputation: 13195

The story is that this is what ObjectMapper-like things inherently do all the time, there is no other way: an object is instantiated first, and then it is updated from the JSON.
The only obstacle is that there is no readValue()-like shortcut for it (it could be something like updateValue()), so it is a few character longer, you need to use readerForUpdating() to get a suitable reader, and then its readValue():

import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
    public String message="Nope";
    public String target="Nope";
    public String toString() {
        return message+" "+target+"!";
    }

    public static void main(String[] args) throws Exception {
        Test test=new Test();
        System.out.println(test);
        ObjectMapper mapper=new ObjectMapper();
        mapper.readerForUpdating(test).readValue("{\"message\":\"Hello\"}");
        System.out.println(test);
        mapper.readerForUpdating(test).readValue("{\"target\":\"World\"}");
        System.out.println(test);
    }
}

Output:

Nope Nope!
Hello Nope!
Hello World!


Edit: if it is needed repeatedly, the reader can be stored and re-used of course:

ObjectReader reader=mapper.readerForUpdating(test);
reader.readValue("{\"message\":\"Hello\"}");
System.out.println(test);
reader.readValue("{\"target\":\"World\"}");
System.out.println(test);

Upvotes: 1

abj1305
abj1305

Reputation: 665

I was having the same question and after a lot of digging into the dirt I came across an open source library, MapStruct. It helps in java beans mapping and generates code for you at the time your application boots up. It worked fine for me. Give it a go.

Upvotes: 0

Related Questions