Cris Benois Cris Benois - 4 months ago 10
Java Question

Java model for json

I want to parse a nested json where the father key contains two different nested key-objects (not a single model which could be abstracted and serialized in a list).

What would be a correct Java model (corresponding class) for this example Json?

{
"name" : "Jack",
"surname" : "Hopper",
"address" : "711-2880 Nulla St. Mankato Mississippi 96522",
"FatherKey" :
{
"ChildKeyNo1" :
{
"defaultKey" : "2_s_g",
"key1" : "4_s_g",
"key2" : "2_s_g"
},
"ChildKeyNo2" :
{
"defaultKey" : "4_s_g",
"key1" : "6_s_g",
"key2" : "7_s_g"
}
}
}


I've come up with:

public class MainJsonConfiguration{
private String name;
private String surname;
private String address;
private FatherKey fatherKey;

public MainJsonConfiguration(String name, String surname, String address, String fatherKey){
this.name = name;
this.surname = surname;
this.address = address;
this.fatherKey = new FatherKey(new ChildKey(), new ChildKey());
}
}

public class FatherKey{

private ChildKey childKey1;
private ChildKey childKey2;

public FatherKey(ChildKey childKey1, ChildKey childKey2){
this.childKey1 = childKey1;
this.childKey2 = childKey2;
}
}

public class ChildKey{

private String defaultKey;
private String key1;
private String key2;

public ChildKey(){
}
}


but it smells fishy....

any suggestions?

Thank you very much

Answer

You can use FasterXML Jackson with the annotation JsonProperty to define the name of the properties to inject in the constructors.

Here how your class could look like:

public class MainJsonConfiguration{
    private String name;
    private String surname;
    private String address;
    private FatherKey fatherKey;

    public MainJsonConfiguration(@JsonProperty("name") String name,
        @JsonProperty("surname") String surname,
        @JsonProperty("address") String address,
        @JsonProperty("FatherKey") FatherKey fatherKey){
        this.name = name;
        this.surname = surname;
        this.address = address;
        this.fatherKey = fatherKey;

    }
}

public class FatherKey{

    private ChildKey childKey1;
    private ChildKey childKey2;

    public FatherKey(@JsonProperty("ChildKeyNo1") ChildKey  childKey1,
        @JsonProperty("ChildKeyNo2") ChildKey  childKey2){
        this.childKey1 = childKey1;
        this.childKey2 = childKey2;
    }
}

public class ChildKey{

    private String defaultKey;
    private String key1;
    private String key2;

    public ChildKey(@JsonProperty("defaultKey") String defaultKey,
        @JsonProperty("key1") String key1,
        @JsonProperty("key2") String key2){
        this.defaultKey = defaultKey;
        this.key1 = key1;
        this.key2 = key2;
    }
}

Here is the code to parse your JSON:

ObjectMapper mapper = new ObjectMapper();
MainJsonConfiguration configuration = mapper.readValue(
    jsonString, MainJsonConfiguration.class
);