如何使用Moshi将int数组反序列化为自定义类? [英] How to deseralize an int array into a custom class with Moshi?

查看:94
本文介绍了如何使用Moshi将int数组反序列化为自定义类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

这按预期工作.

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

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

}

使用自定义类型适配器还是其他可能?

推荐答案

我想到了此适配器:

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

}

这篇关于如何使用Moshi将int数组反序列化为自定义类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆