LoginSignup
4
2

More than 5 years have passed since last update.

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ とは(備忘録)

Last updated at Posted at 2017-04-14

はじめに

Android開発でHTTPSのGETリクエストは必然的になってきます.
HTTPSのGETリクエストを行い,それに対するレスポンスが返ってきます.
今回は返ってきた結果がJSON文字列であるときのお話です.

参考

こちらを参考にしました.
http://qiita.com/furusin_oriver/items/59dd0ae6dc795737eded
いざ実行!

エラー:frowning2:

terminal
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

原因

原因は取得したJSON文字列の書式問題でした.
つまり用意している格納変数は

sample1
{
  "name": "Name",
  "todofuken": 36,
  "address": 1,
  "img_url": "https://xxx.s3.amazonaws.com/uploads/user/foo.jpg?xxx..."
}

であれば成功していたけど,

sample2
[
 {
  "name": "Name1",
  "todofuken": 36,
  "address": 1,
  "img_url": "https://xxx.s3.amazonaws.com/uploads/user/foo.jpg?xxx..."
}
,
{
  "name": "Name2",
  "todofuken": 36,
  "address": 1,
  "img_url": "https://xxx.s3.amazonaws.com/uploads/user/foo.jpg?xxx..."
},

.
.
.

,
{
  "name": "NameN",
  "todofuken": 36,
  "address": 1,
  "img_url": "https://xxx.s3.amazonaws.com/uploads/user/foo.jpg?xxx..."
}
]

のように配列のようになっていたのが原因でした.
もっと簡単に大袈裟にいうと

int x;
ArrayList<String> array = new ArrayList<String>();
x = array;//エラー

みたいな感じになっているのが原因でした.
そりゃ型が合わないと変数は入れれませんよね...:sweat:

解決策

解決策としてはその


int x;
ArrayList<String> array = new ArrayList<String>();
x = array;//エラー

ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>(array1);

みたいな感じで型を合わせてやればいいといきつきました.

結論

レスポンスを格納する変数を全てArrayListにしてください.

余談

Java初心者で,不具合等ございますが,ご了承ください.

4
2
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
4
2