Moshi Date Adapter begin_object但是是begin_array

问题描述 投票:0回答:1

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

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

DateAdapter:

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个回答
0
投票

您的json是从数组开始的,因此您必须在接口中在数组中设置您的改造响应(在Java中为this ans):-Call<List<ItemList>> getHomeContent();

© www.soinside.com 2019 - 2024. All rights reserved.