yong ho
yong ho

Reputation: 4042

Fuel, Kotlin, Gson, Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1

I'm trying to parse a JSON string like this:

{
    "count": 1,
    "items": [
        {
            "organization_id": 6972979,
            "organization_name": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
        }
    ]
}

And the Kotlin class:

class LoremModel {
    var count: Int? = null
    var items: List<Lorem>? = null

    class Lorem {
        var organization_id: Int? = null
        var organization_name: String? = null

        constructor(organization_id: Int?,  organization_name: String?) {
            this.organization_id = organization_id
            this.organization_name = organization_name
        }
    }

    class ListDeserializer : ResponseDeserializable<List<LoremModel>> {
        override fun deserialize(content: String) = Gson().fromJson<List<LoremModel>>(content, object : TypeToken<List<LoremModel>>() {}.type)
    }
}

The Fuel part:

Fuel.get("/lorem/search", listOf("keywords" to  keyword, "category" to category, "pageNum" to "1", "pageSize" to "10")).
        responseObject(LoremModel.ListDeserializer()) { request, _, item ->
        }

But I am getting an error:

[Failure: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $]

How do I solve it?

Upvotes: 2

Views: 2039

Answers (1)

jayeshsolanki93
jayeshsolanki93

Reputation: 2136

Your json

{
    "count": 1,
    "items": [
        {
            "organization_id": 6972979,
            "organization_name": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
        }
    ]
}

represents a JSON Object and not a JSON Array.

So instead of trying to deserialize it into a type of List of LoremModel objects

Gson().fromJson<List<LoremModel>>(content, object : TypeToken<List<LoremModel>>() {}.type)

You should deserialize it to an object of type LoremModel. So you can do this:

Gson().fromJson(content, LoremModel::class.java)

Upvotes: 2

Related Questions