使用Retrofit将json结构转换为数组

时间:2014-08-02 23:55:27

标签: java gson retrofit

我在Trakt.tv API中遇到了Retrofit和一个丑陋的json对象:

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

"发作"内容显然是动态的,我想将它作为一个简单的布尔数组处理,如下所示:

int season;
Boolean[] episodes;

怎么做?

2 个答案:

答案 0 :(得分:2)

您可以先将JSON字符串转换为Map<String,Object>,然后最终创建所需的对象。

示例代码:

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));

输出:

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

使用 GSON Deserialiser

再一种方法

示例代码:

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));

请参阅How do I write a custom JSON deserializer for Gson?

答案 1 :(得分:0)

当我使用jackson库来解析该JSON时,我使用ObjectMapperDramaInfo类,如下所示。

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();
        }
    }
}

所以,这是一个建议,因为我从未使用过Retrofit。如果您要按照以下方式使用Retrofit,那么如何尝试上面显示的DramaInfo类呢?

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