How to deseralize an int array into a custom class

2019-09-08 14:47发布

问题:

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

}