user1950349
user1950349

Reputation: 5146

serialize json array into java objects

I have a JSON array like as shown below which I need to serialize it to my class. I am using Jackson in my project.

[
    {
        "clientId": "111",
        "clientName": "mask",
        "clientKey": "abc1",
        "clientValue": {}
    },
    {
        "clientId": "111",
        "clientName": "mask",
        "clientKey": "abc2",
        "clientValue": {}
    }
]

In above JSON array, clientValue will have another JSON object in it. How can I serialize my above JSON array into my java class using Jackson?

public class DataRequest {
    @JsonProperty("clientId")
    private String clientId;

    @JsonProperty("clientName")
    private int clientName;

    @JsonProperty("clientKey")
    private String clientKey;

    @JsonProperty("clientValue")
    private Map<String, Object> clientValue;

    //getters and setters
}

I have not used jackson before so I am not sure how can I use it to serialize my JSON array into Java objects? I am using jackson annotation here to serialize stuff but not sure what will be my next step?

Upvotes: 0

Views: 1605

Answers (2)

Nailgun
Nailgun

Reputation: 4169

You can try @JsonAnyGetter and @JsonAnySetter annotations with an inner class object. Also clientName should have type String, not int.

public class DataRequest {

    private String clientId;

    private String clientName;

    private String clientKey;

    private ClientValue clientValue;

    //getters and setters
}

public class ClientValue {

    private Map<String, String> properties;

    @JsonAnySetter 
    public void add(String key, String value) {
        properties.put(key, value);
    }

    @JsonAnyGetter 
    public Map<String,String> getProperties() {
        return properties;
    } 

}

Upvotes: 1

Amir
Amir

Reputation: 486

You can create a utility function shown below. You may want to change the Deserialization feature based on your business needs. In my case, I did not want to fail on unknown properties => (FAIL_ON_UNKNOWN_PROPERTIES, false)

static <T> T mapJson(String body, 
                     com.fasterxml.jackson.core.type.TypeReference<T> reference) {
    T model = null;

    if(body == null) {
        return model;
    }

    com.fasterxml.jackson.databind.ObjectMapper mapper = 
         new com.fasterxml.jackson.databind.ObjectMapper();

    mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, 
                     false);
    try {
        model = mapper.readValue(body, reference);
    } catch (IOException e) {
        //TODO: log error and handle accordingly
    }

    return model;
}

You can call it using similar approach as shown below:

mapJson(clientValueJsonString, 
        new com.fasterxml.jackson.core.type.TypeReference<List<DataRequest>>(){});

Upvotes: 1

Related Questions