Search code examples
androidjsonrestretrofitreddit

How to handle the deeply nested json response of reddit apis in android?


I am trying to consume the Reddit API in android. I am currently using Retrofit with GSon.

One of the endpoints which I am dealing with has a very complex API response.

https://oauth.reddit.com/subreddits/popular

Here's what the API response looks like: https://gist.github.com/roysailor/c991d8a854c064cbc48e2ee2d2ad2b69

I have tried creating a model class for it but it seems to be a very lengthy process.

Other options are using POJO generators or manual JSON Parsing.

What do you suggest is the best way to handle such a response?


Solution

  • I think "the best way to handle this" is opinion-based, but out of curiosity I copy-pasted your raw JSON into jsonschema2pojo.org and it yielded 4 classes describing your data (so it's not that complex).

    You could definitely import them in your codebase, since Reddit API is unlikely to change its model without warning you.

    Child.java
    Data.java // You should probably rename this
    Data_.java // This aswell 
    Example.java
    

    Example.java :

    
    package com.example;
    
    import java.util.HashMap;
    import java.util.Map;
    import com.fasterxml.jackson.annotation.JsonAnyGetter;
    import com.fasterxml.jackson.annotation.JsonAnySetter;
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({
        "kind",
        "data"
    })
    public class Example {
    
        @JsonProperty("kind")
        private String kind;
        @JsonProperty("data")
        private Data data;
        @JsonIgnore
        private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
        @JsonProperty("kind")
        public String getKind() {
            return kind;
        }
    
        @JsonProperty("kind")
        public void setKind(String kind) {
            this.kind = kind;
        }
    
        @JsonProperty("data")
        public Data getData() {
            return data;
        }
    
        @JsonProperty("data")
        public void setData(Data data) {
            this.data = data;
        }
    
        @JsonAnyGetter
        public Map<String, Object> getAdditionalProperties() {
            return this.additionalProperties;
        }
    
        @JsonAnySetter
        public void setAdditionalProperty(String name, Object value) {
            this.additionalProperties.put(name, value);
        }
    
    }
    
    

    Feel free to fiddle around with the parameters to suit your codebase better.