Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON into existing object (Java)

I'd like to know how one might get the Jackson JSON library to deserialize JSON into an existing object? I've tried to find how to to this; but it seems to only be able to take a Class and instantiate it itself.

Or if not possible, I'd like to know if any Java JSON deserialization libraries can do it.

This seems to be a corresponding question for C#: Overlay data from JSON string to existing object instance. It seems JSON.NET has a PopulateObject(string,object).

like image 821
Jonas N Avatar asked Sep 20 '12 18:09

Jonas N


3 Answers

You can do this using Jackson:

mapper.readerForUpdating(object).readValue(json); 

See also Merging Two JSON Documents Using Jackson

like image 153
Johan Boberg Avatar answered Sep 18 '22 19:09

Johan Boberg


If you can use another library instead of Jackson you can try Genson http://owlike.github.io/genson/. In addition of some other nice features (such as deserialize using a non empty constructor without any annotation, deserialize to polymorphic types, etc) it supports deserialization of JavaBean into an existing instance. Here is an example:

BeanDescriptorProvider provider = new Genson().getBeanDescriptorFactory(); BeanDescriptor<MyClass> descriptor = provider.provide(MyClass.class, genson); ObjectReader reader = new JsonReader(jsonString); MyClass existingObject = descriptor.deserialize(existingObject, reader, new Context(genson)); 

If you have any question don't hesitate to use its mailing list http://groups.google.com/group/genson.

like image 39
eugen Avatar answered Sep 20 '22 19:09

eugen


If you are using spring framework you can use BeanUtils library for this task. First deserialize your json String normally and then use BeanUtils to set this object inside a parent object. It also expects the variable name of the object to be set inside the parent object. Here is the code snippet:

childObject = gson.fromJson("your json string",class.forName(argType))
BeanUtils.setProperty(mainObject, "childObjectName", childObject);
like image 34
yokesh sharma Avatar answered Sep 20 '22 19:09

yokesh sharma