Details
-
Type:
New Feature
-
Status:
Resolved
-
Priority:
Minor
-
Resolution: Fixed
-
Affects Version/s: None
-
Fix Version/s: None
-
Component/s: Deserializer
-
Labels:None
-
Number of attachments :
Description
ObjectMapper already serializes inner classes, by default, without any special settings and without custom processing, but there is no simple mechanism to similarly deserialize from JSON.
To complement the existing serialization behavior, deserialization handling to instantiate inner classes from JSON should be provided.
The following code demonstrates the inner class serialization capability already available through ObjectMapper. This code also demonstrates the desired deserialization functionality.
class Dog
{
public String name;
public Brain brain;
public class Brain {public boolean isThinking;}
}
public class Foo
{
public static void main(String[] args) throws Exception
{
Dog dog = new Dog();
dog.name = "Spike";
dog.brain = dog.new Brain();
dog.brain.isThinking = true;
ObjectMapper mapper = new ObjectMapper();
String dogJson = mapper.writeValueAsString(dog);
System.out.println(dogJson);
// output: {"name":"Spike","brain":{"isThinking":true}}
String brainJson = mapper.writeValueAsString(dog.brain);
System.out.println(brainJson);
// output: {"isThinking":true}
// currently throws JsonMappingException
Dog dogCopy = mapper.readValue(dogJson, Dog.class);
// prefer fully populated Dog instance
// currently throws JsonMappingException
Dog.Brain brainCopy = mapper.readValue(brainJson, Dog.Brain.class);
// prefer a Dog.Brain instance, where the outer field values are defaults
// as if the following code were executed
Dog.Brain brainWanted = new Dog().new Brain();
brainWanted.isThinking = true; // populated from JSON input
}
}
Actually ValueInstantiator can not deal with this, as the parent instance is not passed during deserialization.
But I was able to handle this through BeanDeserializer/SettableBeanProperty as parent POJO is available at this point; and basic unit tests confirm functionality.
Will be included in 1.9.0.