Search code examples
javaandroidjsonretrofitpojo

Dynamic Json Response mapping to Pojo


I am using an API which returns a dynamic amount of JSON keys for a given response (let's say the minimum is 20 and the maximum 30 keys). I know all possible keys in advance, I just don't know how many will be returned for a given response.

How do I map those fields to a POJO that has the maximum amount of fields (30) with all missing fields being null. So if the response contains 20 keys, I would like the POJO to populate all its fields with the corresponding values from the JSON while the other 10 fields in the POJO remain null.

Currently I am using Retrofit and GSON, but I'll be glad to change if I find a way to do this with other libraries.


Solution

  • Using jackason

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    ...
    
    static class Data {
        public String k1;
        public String k2;
        public String k3;
        // ...
        public String kN;
    }
    
    public static void main(String[] args) throws JsonProcessingException {
        Data data = new ObjectMapper().readValue("{\"k2\": \"value2\"}", Data.class);
        System.out.printf("%s, %s, %s, ...%n", data.k1, data.k2, data.k3);
    }
    

    with output

    null, value2, null, ...