Reputation: 118
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
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!
ObjectReader reader=mapper.readerForUpdating(test);
reader.readValue("{\"message\":\"Hello\"}");
System.out.println(test);
reader.readValue("{\"target\":\"World\"}");
System.out.println(test);
Upvotes: 1