如何使用 Moshi 将 int 数组反序列化为自定义 class?
How to deseralize an int array into a custom class with Moshi?
我使用 Moshi 反序列化以下 JSON 文件:
{
"display": "Video 1",
"isTranslated": false,
"videoSize": [
1920,
1080
]
}
...使用以下模型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;
}
}
这按预期工作。
现在,我想 替换 int[]
为专用的 VideoSize
class ,它将两个整数值映射到命名字段如:
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 或其他方式是否可行?
我想到了这个适配器:
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 反序列化以下 JSON 文件:
{
"display": "Video 1",
"isTranslated": false,
"videoSize": [
1920,
1080
]
}
...使用以下模型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;
}
}
这按预期工作。
现在,我想 替换 int[]
为专用的 VideoSize
class ,它将两个整数值映射到命名字段如:
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 或其他方式是否可行?
我想到了这个适配器:
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);
}
}