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).
You can do this using Jackson:
mapper.readerForUpdating(object).readValue(json);
See also Merging Two JSON Documents Using Jackson
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With