0

I'm using the retrofit and moshi library in my project to help me connect to my backend. From there, I sent dates back but apparently, moshi can't handle dates. I've written my own JsonAdapter but now I get the error:

com.squareup.moshi.JsonDataException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at path $

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))
    }

}

Network layer

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>

Example response:

[
    {
        "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
    }
]

I've done some research and most talk about the fact that you get an array instead of a single object and that something needs to change but I don't know what or to add @Wrapped

Mout Pessemier
  • 1,665
  • 3
  • 19
  • 33
  • Possible duplicate of [Retrofit Expected BEGIN\_OBJECT but was BEGIN\_ARRAY](https://stackoverflow.com/questions/24154917/retrofit-expected-begin-object-but-was-begin-array) – Shashanth Nov 11 '19 at 09:48

1 Answers1

0

your json is starting with array so you have to set your retrofit response in array like this in interface (This ans in JAVA) :- Call<List<ItemList>> getHomeContent();

Sandeep Malik
  • 1,972
  • 1
  • 8
  • 17