Moshi日期适配器begin_object但是begin_array DateAdapter:网络层示例响应:

我在项目中使用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

lookme123 回答:Moshi日期适配器begin_object但是begin_array DateAdapter:网络层示例响应:

您的json以数组开头,因此您必须在接口(在Java中为This ans)的数组中设置改型响应:-Call<List<ItemList>> getHomeContent();

本文链接:https://www.f2er.com/3125331.html

大家都在问