Moshi:期望Class,ParameterizedType或GenericArrayType,但<null>的类型为null

时间:2017-12-12 08:16:19

标签: android kotlin moshi

我有这个型号:

class Model1 {
    <... other fields here ...>
    var attributes: Map<String, Any>? = null
    <... other fields here ...>
}

我期待这些模型的列表。

示例JSON:

[
    {
        "attributes": {
            "title": "New Year's Day",
            "country": "SG"
        }
    },
    {
        "attributes": {
            "staff_id": 320011,
            "title": "Labor day",
            "date_joined": "2017-01-10 00:00:00",
            "years": 1
        }
    }
]

然后在反序列化期间出现此错误:

Caused by: java.lang.IllegalArgumentException: Expected a Class, ParameterizedType, or GenericArrayType, but <null> is of type null
    at com.squareup.moshi.Types.getRawType(Types.java:165)
    at com.squareup.moshi.ClassJsonAdapter$1.createFieldBindings(ClassJsonAdapter.java:82)
    at com.squareup.moshi.ClassJsonAdapter$1.create(ClassJsonAdapter.java:74)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:99)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:57)
    at com.squareup.moshi.MapJsonAdapter.<init>(MapJsonAdapter.java:46)
    at com.squareup.moshi.MapJsonAdapter$1.create(MapJsonAdapter.java:37)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:99)
    at com.squareup.moshi.ClassJsonAdapter$1.createFieldBindings(ClassJsonAdapter.java:90)
    at com.squareup.moshi.ClassJsonAdapter$1.create(ClassJsonAdapter.java:74)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:99)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:57)
    at com.squareup.moshi.CollectionJsonAdapter.newArrayListAdapter(CollectionJsonAdapter.java:51)
    at com.squareup.moshi.CollectionJsonAdapter$1.create(CollectionJsonAdapter.java:35)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:99)
    at com.squareup.moshi.ClassJsonAdapter$1.createFieldBindings(ClassJsonAdapter.java:90)
    at com.squareup.moshi.ClassJsonAdapter$1.create(ClassJsonAdapter.java:74)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:99)
    at retrofit2.converter.moshi.MoshiConverterFactory.responseBodyConverter(MoshiConverterFactory.java:91)
    at retrofit2.Retrofit.nextResponseBodyConverter(Retrofit.java:330)
    at retrofit2.Retrofit.responseBodyConverter(Retrofit.java:313)
    at retrofit2.ServiceMethod$Builder.createResponseConverter(ServiceMethod.java:736)
        ... 65 more

我需要将field属性作为地图。里面的数据可以是任何类型和任何值

2 个答案:

答案 0 :(得分:5)

您希望地图参数为@JvmSuppressWildcardshttps://github.com/square/moshi/issues/410#issuecomment-351131524

希望在下一版Moshi中出现更好的错误信息。

答案 1 :(得分:2)

只需要这样做:

class Model1 {
    <... other fields here ...>
    @JvmSuppressWildcards var attributes: Map<String, Any>? = null
    <... other fields here ...>
}

https://github.com/square/moshi/issues/410#issuecomment-351131524