0

我使用Moshi反序列化以下 JSON 文件:

{
    "display": "Video 1",
    "isTranslated": false,
    "videoSize": [
        1920,
        1080
    ]
}

...使用以下模型类:

public class Stream {

    public final String display;
    public final boolean isTranslated;
    public final int[] videoSize;

    public Stream(String display,
                  boolean isTranslated,
                  int[] videoSize) {
        this.display = display;
        this.isTranslated = isTranslated;
        this.videoSize = videoSize;
    }

}

这按预期工作。


现在,我想用一个将两个整数值映射到命名字段的专用类替换,例如:int[]VideoSize

public class VideoSize {

    public final int height;
    public final int width;

    public VideoSize(int width, int height) {
        this.height = height;
        this.width = width;
    }

}

这可以通过自定义类型适配器或其他方式实现吗?

4

1 回答 1

1

我想出了这个适配器:

public class VideoSizeAdapter {

    @ToJson
    int[] toJson(VideoSize videoSize) {
        return new int[]{videoSize.width, videoSize.height};
    }

    @FromJson
    VideoSize fromJson(int[] dimensions) throws Exception {
        if (dimensions.length != 2) {
            throw new Exception("Expected 2 elements but was " + 
                Arrays.toString(dimensions));
        }
        int width = dimensions[0];
        int height = dimensions[1];
        return new VideoSize(width, height);
    }

}
于 2015-11-25T16:06:39.637 回答