1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Retrofit2でExpected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $エラー

Posted at

#背景
Retrofit2 + gsonでQiita API v2の投稿記事一覧の取得を試したときに

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

というエラーが出た。
調べてみたら、ピンポイントな解決法がなかなか見つからなかったので備忘録

#原因
エラーに出てる通り、ArrayからはじまるjsonをObjectから受け取ろうとしていた。

.json
[
    {
        "rendered_body": "...",
        "body": "...",
        ...以下略
    },
    {
        "rendered_body": ">\n",
        "body": "_!\n",
        ...以下略
    }
    ...以下略
]
ApiService.kt
@GET("/api/v2/items")
fun getItems(): Call<ItemsResponse>
ItemsResponse.kt
data class ItemsResponse(

        @SerializedName("rendered_body")
        val renderedBody: String,

        @SerializedName("body")
        val body: String,
//...以下略
)

#解決

ApiService.kt
@GET("/api/v2/items")
fun getItems(): Call<Array<ItemsResponse>>

#参考
http://square.github.io/retrofit/
https://qiita.com/api/v2/docs
https://stackoverflow.com/questions/26472529/expected-begin-object-but-was-begin-array-at-line-1-column-2-path

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?