Convert json structure to array using retrofit

I am having problems with Retrofit and ugly json object in Trakt.tv API:

{
    "season": 1,
    "episodes": {
        "1": true,
        "2": true,
        "3": false,
        "4": false,
        "5": false,
        "6": false,
        "7": false
    }
}

      

The "episodes" content is obviously dynamic and I would like to treat it as a simple boolean array, for example:

int season;
Boolean[] episodes;

      

How to do it?

+3


source to share


2 answers


You can convert the JSON string to first Map<String,Object>

, then create the object you want .

example code:

public class EpisodesDetail {
    private int season;
    private Boolean[] episodes;
    // getter & setter 
}
...

BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> map = new Gson().fromJson(reader, type);

EpisodesDetail geometry = new EpisodesDetail();
geometry.setSeason(((Double) map.get("season")).intValue());
geometry.setEpisodes(((Map<String, Boolean>) map.get("episodes")).values().toArray(
        new Boolean[] {}));

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(geometry));

      

output:

{
  "season": 1,
  "episodes": [
    true,
    true,
    false,
    false,
    false,
    false,
    false
  ]
}

      




There is another approach using Deserialiser GSON

example code:

class EpisodesDetailDeserializer implements JsonDeserializer<EpisodesDetail> {

    @Override
    public EpisodesDetail deserialize(final JsonElement json, final Type typeOfT,
            final JsonDeserializationContext context) throws JsonParseException {

        EpisodesDetail geometry = new EpisodesDetail();
        JsonObject jsonObject = json.getAsJsonObject();
        int season = jsonObject.get("season").getAsInt();
        geometry.setSeason(season);

        List<Boolean> episodes = new ArrayList<Boolean>();
        Set<Entry<String, JsonElement>> set = jsonObject.get("episodes").getAsJsonObject()
                .entrySet();

        Iterator<Entry<String, JsonElement>> it = set.iterator();
        while (it.hasNext()) {
            episodes.add(it.next().getValue().getAsBoolean());
        }
        geometry.setEpisodes(episodes.toArray(new Boolean[] {}));
        return geometry;
    }
}

BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
EpisodesDetail episodesDetail = new GsonBuilder()
        .registerTypeAdapter(EpisodesDetail.class, new EpisodesDetailDeserializer())
        .create().fromJson(reader, EpisodesDetail.class);

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(episodesDetail));

      

See How to write a custom JSON deserializer for Gson?

+2


source


When I use a library jackson

to parse this JSON, I use the class ObjectMapper

and DramaInfo

as follows.

package jackson;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.fasterxml.jackson.databind.ObjectMapper;

class DramaInfo {

    int season;
    List<Boolean> episodes;


    public void setSeason(int season) {
        this.season = season;
    }
    public int getSeason() {
        return this.season;
    }

    public List<Boolean> getEpisodes() {
        return new LinkedList<>( this.episodes );
    }
    public void setEpisodes(Map<String, Boolean> o) {
        // used Java 1.8 Stream.
        // just see http://docs.oracle.com/javase/tutorial/collections/streams/reduction.html
        episodes = o.keySet().stream().map(e -> o.get(e)).collect(Collectors.toList());
    }

    public String toString() {
        String ret = "season: " + this.season + "\n";
        ret += this.episodes.toString();
        return ret;
    }
}

public class LoadJsonData {

    public static void main(String[] args) {
        String toConvert = "{\"season\": 1, \"episodes\": { \"1\": true, \"2\": true, \"3\": false, \"4\": false, \"5\": false, \"6\": false, \"7\": false } }";
        ObjectMapper mapper = new ObjectMapper();
        try {
            DramaInfo info = mapper.readValue(toConvert, DramaInfo.class);
            System.out.println(info);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

      



So this is a suggestion because I have never used Retrofit. If you want to use Retrofit in the following way, how about trying the class DramaInfo

shown above?

public interface DramaService {
  @GET("/dramas/{drama}/info")
  DramaInfo listRepos(@Path("drama") String drama);
}

      

0


source







All Articles