LoginSignup
21
28

More than 5 years have passed since last update.

JavaでJSONオブジェクトを扱う

Posted at

APIなどにアクセスして情報を取得する場合、レスポンスにJSONの形で入ってくることがあります。その場合、Java言語では以下のような手順で扱います。

JSON受け取り

1.レスポンス受け取り
2.レスポンス文字列をJSONオブジェクトに変換
3.JSONオブジェクトをパースする

以下に例を示します。

レスポンスで受け取る文字列

[
  {
    "id": 1,
    "name": "post1",
    "price": 1501,
    "kind": 3,
    "kind_value": "ランチ",
    "user_value": null,
    "play": "2016-01-24T00:01:12.000Z",
    "lon": null,
    "lat": null,
    "created_at": "2016-01-24T12:25:52.000Z",
    "updated_at": "2016-01-24T12:25:52.000Z"
  },
  {
    "id": 2,
    "name": "post2",
    "price": 1502,
    "kind": 4,
    "kind_value": "ブランチ",
    "user_value": null,
    "play": "2016-01-23T00:01:12.000Z",
    "lon": null,
    "lat": null,
    "created_at": "2016-01-24T12:26:05.000Z",
    "updated_at": "2016-01-24T12:26:05.000Z"
  }
]

Javaのソースコード

//レスポンスの文字列をJSONオブジェクトに変換
JSONArray jsonArray = new JSONArray(レスポンス文字列);
for (int i = 0; i < jsonArray.length(); i++) {
  //JSONオブジェクトをパースして、レコードのname属性をログ出力
  JSONObject jsonObject = jsonArray.getJSONObject(i);
  Log.d("HTTP REQ", jsonObject.getString("name"));
}

Log.dで、JSONのレコード毎にname属性を出力しています。

21
28
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
21
28