Deserializing nested JSON to Java object

1,967 views
Skip to first unread message

PA

unread,
Jul 31, 2015, 6:40:53 PM7/31/15
to jackson-user
Hello,
This is the JSON file I want to convert into Java object
{
 
"personal": {
   
"name": "John Doe",
   
"age": "28",
   
"gender": "male",
 
}
 
"address": {
   
"street": "123 main st",
   
"state": "md",
   
"zipcode": "21228"
 
}
}



The java object im creating is
public class customerInfo{
   
private String infoType;
   
private Map<String, String>;
}


So basically what I want is a List<customerInfo> where
element 1:
infoType = personal 
Map = <name, John Doe>, and so on

element 2:
infoType = address
Map = <street, 123 main st>, and so on

This is what I've been trying so far but couldn't get it to work
customerInfo customer = mapper.readValue(new File("jsonTestFile.json"), customerInfo.class);
I only put the first portion of the test file to test that line of code.
So the jsonTestFile.json content is
{
 
"personal": {
   
"name": "John Doe",
   
"age": "28",
   
"gender": "male",
 
}
}


so how do I deserializing the json object in both scenarios?
Thank you very much

Ben Vesco

unread,
Jul 31, 2015, 7:52:39 PM7/31/15
to jackson-user
That's a complex example. You're trying to take the property name of a parent object and make it a property value of a child object. This is possible with Jackson but is a more advanced example than I can provide. Using your object:

public class customerInfo{
   
private String infoType;

   
private Map<String, String> data;
}

You would more naturally support jsonTestFile.json looking like:
{
  
"infoType": "personal",
  "data": {
--
You received this message because you are subscribed to the Google Groups "jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jackson-user...@googlegroups.com.
To post to this group, send email to jackso...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tatu Saloranta

unread,
Aug 1, 2015, 5:09:23 PM8/1/15
to jackso...@googlegroups.com
I agree in that it is often much easier to modify JSON, or Java object definitions (or sometimes both), instead of trying to apply complicated conversion logic. Databinding is indeed designed to bind compatible structures into each other; and not as a general-purpose transformation engine.

-+ Tatu +-

Reply all
Reply to author
Forward
0 new messages