【问题标题】:How to deseralize an int array into a custom class with Moshi?如何使用 Moshi 将 int 数组反序列化为自定义类?
【发布时间】:2016-02-28 11:49:16
【问题描述】:

我使用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;
    }

}

custom type adapter 或其他方式可以做到这一点吗?

【问题讨论】:

    标签: java json json-deserialization moshi


    【解决方案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);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 2017-04-18
      • 1970-01-01
      • 2019-04-03
      • 2020-10-17
      • 2019-03-05
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多