【问题标题】:Moshi Date Adapter begin_object but was begin_arrayMoshi 日期适配器 begin_object 但被 begin_array
【发布时间】:2020-03-06 23:32:08
【问题描述】:

我在我的项目中使用retrofitmoshi 库来帮助我连接到我的后端。从那里,我发回了日期,但显然,moshi 无法处理日期。我已经编写了自己的 JsonAdapter,但现在出现错误:

com.squareup.moshi.JsonDataException:预期为 BEGIN_OBJECT,但在路径 $ 处是 BEGIN_ARRAY

日期适配器:

class DateAdapter: JsonAdapter<Date>() {
    @FromJson
    override fun fromJson(reader: JsonReader): Date? {
        val value = reader.nextString()
        return SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH).parse(value)
        //return getDateInstance(DateFormat.LONG, Locale.FRENCH).parse(value)
    }

    @ToJson
    override fun toJson(writer: JsonWriter, value: Date?) {
        writer.value(SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH).format(value))
    }

}

网络层

private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .add(DateAdapter())
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .addCallAdapterFactory(CoroutineCallAdapterFactory())
    .baseUrl(BASE_URL)
    .build()

// the request that throws the error
@GET("getPartiesNearYou")
fun getPatiesNearYou(
    @Query("distance") distance: Int,
    @Query("lat") lat: Double,
    @Query("long") long: Double,
    @Query("userId") userId: String
): Deferred<NetworkPartyContainer>

示例响应:

[
    {
        "location": {
            "type": "Point",
            "coordinates": [
                50,
                50
            ]
        },
        "participants": [
            "5db76b7430957f0ef05e73fa"
        ],
        "declines": [
            null,
            "5dc322e02c7171369e4c67fb"
        ],
        "_id": "5dc322712c7171369e4c67fa",
        "name": "Mout's Hartenjagen Party",
        "date": "2019-11-28T23:00:00.000Z",
        "maxSize": 4,
        "gameId": "5db76b7430957f0ef05e73fa",
        "createdAt": "2019-11-06T19:43:45.544Z",
        "updatedAt": "2019-11-06T19:49:07.599Z",
        "__v": 0
    }
]

我做了一些研究,大多数人都在谈论这样一个事实,即你得到一个数组而不是单个对象,并且需要改变一些东西,但我不知道要添加什么或添加 @Wrapped

【问题讨论】:

标签: android kotlin retrofit2 moshi


【解决方案1】:

您的 json 以数组开头,因此您必须在接口中像这样在数组中设置改造响应(Java 中的 This ans):- Call&lt;List&lt;ItemList&gt;&gt; getHomeContent();

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 2020-12-10
    • 2020-03-23
    • 2017-09-05
    • 2015-07-24
    • 2019-05-10
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多