どこが間違っているのかわかりません。
私の単純なモデルは次のようになります。
final class Data {
final int num;
Data(int num) {
this.num = num;
}
static final class Wrapper {
final List<Data> data;
final long meta;
Wrapper(List<Data> data, long meta) {
this.data = data;
this.meta = meta;
}
}
}
Data
そして私の工場はから引き抜くWrapper
:
final class ObjectAsListJsonAdapterFactory implements JsonAdapter.Factory {
@Override public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
if (!List.class.isAssignableFrom(Types.getRawType(type))) {
return null;
}
JsonAdapter<List<Object>> listDelegate = moshi.nextAdapter(this, type, annotations);
Type innerType = Types.collectionElementType(type, List.class);
JsonAdapter<Object> objectDelegate = moshi.adapter(innerType, annotations);
return new ListJsonAdapter<>(listDelegate, objectDelegate);
}
static final class ListJsonAdapter<T> extends JsonAdapter<List<T>> {
private final JsonAdapter<List<T>> listDelegate;
private final JsonAdapter<T> objectDelegate;
ListJsonAdapter(JsonAdapter<List<T>> listDelegate, JsonAdapter<T> objectDelegate) {
this.listDelegate = listDelegate;
this.objectDelegate = objectDelegate;
}
@Override public List<T> fromJson(JsonReader jsonReader) throws IOException {
if (jsonReader.peek() == JsonReader.Token.BEGIN_OBJECT) {
return Collections.singletonList(objectDelegate.fromJson(jsonReader));
} else {
return listDelegate.fromJson(jsonReader);
}
}
@Override public void toJson(JsonWriter jsonWriter, List<T> list) throws IOException {
listDelegate.toJson(jsonWriter, list);
}
}
}
しかし、私が実行すると:
String json = "{\n"
+ " \"data\": [\n"
+ " {\n"
+ " \"num\": 5\n"
+ " }\n"
+ " ],\n"
+ " \"meta\": 21\n"
+ "}";
Moshi moshi = new Moshi.Builder().add(new ObjectAsListJsonAdapterFactory()).build();
ParameterizedType type = Types.newParameterizedType(List.class, Data.class);
JsonAdapter<List<Data>> adapter = moshi.adapter(type);
List<Data> expected = adapter.fromJson(json);
expected
Data
valueのnum
フィールドを持つものを含みます0
。
私は何が欠けていますか?