How to deseralize an int array into a custom class with Moshi?

此生再无相见时 提交于 2019-12-12 06:08:20

问题


I use Moshi to deserialize the following JSON file:

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

... using the following model class:

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

}

This works as expected.


Now, I would like to replace the int[] with a dedicated VideoSize class which maps the two integer values into named fields such as:

public class VideoSize {

    public final int height;
    public final int width;

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

}

Is this possible with a custom type adapter or somehow else?


回答1:


I came up with this adapter:

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

}


来源:https://stackoverflow.com/questions/33920735/how-to-deseralize-an-int-array-into-a-custom-class-with-moshi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!