Help us understand the problem. What is going on with this article?

kotlinでJSON扱うならJsonToKotlinClassが便利

More than 1 year has passed since last update.

要約

  • KotlinでJSON扱うときはスキーマに合わせたDataクラスを作るツラいお仕事があるが、JsonToKotlinClassを使うと一発で生成してくれるから最高という話

環境

  • Kotlin 1.2
  • Android Studio

概要

kotlinでJSONを扱うときはDataクラス作成→moshi,koshiで変換が一般的(たぶん)だが、いかんせんDataクラス作るのが面倒

が、JSONなげるといい感じのDataクラスを一発で生成してくれるJsonToKotlinClassというIntelliJプラグインがあった。

68747470733a2f2f706c7567696e732e6a6574627261696e732e636f6d2f66696c65732f393936302f73637265656e73686f745f31383033322e706e67.gif

画像は公式サイトから引用

インストール

Android Studioの場合は メニューのPreferences→Plugins→Browse Repositoriesボタンクリック→「JsonToKotlinClass」で検索→インストール&再起動

使い方

適当なところでメニューよりCode→Generate すると「Convert Json to into kotlin class」が表示されるので選択

以下のようなJSONがあったとする。

{
  "results_returned": 10,
  "events": [
    {
      "event_url": "https://itpropartners.connpass.com/event/85351/",
      "event_type": "participation",
      "owner_nickname": "itpropartners",
      "series": {
        "url": "https://itpropartners.connpass.com/",
        "id": 4647,
        "title": "ITPRO PARTNERS Inc."
      },
      "updated_at": "2018-04-29T13:44:53+09:00",
      "lat": "35.656586100000",
      "started_at": "2018-05-19T11:00:00+09:00",
      "hash_tag": "",
      "title": "【初心者・1人参加歓迎】ITプロラボもくもく会(Web系)#5",
      "event_id": 85351,
      "lon": "139.697326400000",
      "waiting": 0,
      "limit": 45,
      "owner_id": 179248,
      "owner_display_name": "ITPRO PARTNERS Inc.",
      "description": "<h3>イベント内容</h3>(略)",
      "address": " 東京都渋谷区 道玄坂1-16-10 (渋谷DTビル8階)",
      "catch": "",
      "accepted": 30,
      "ended_at": "2018-05-19T20:00:00+09:00",
      "place": "株式会社ITプロパートナーズ"
    },
    {
      "event_url": "https://gdg.connpass.com/event/85940/",
      "event_type": "participation",
      "owner_nickname": "kenz",
      "series": {
        "url": "https://gdg.connpass.com/",
        "id": 1996,
        "title": "GoogleDeveloperGroups Kyushu"
      },
      "updated_at": "2018-04-28T11:16:08+09:00",
      "lat": "33.588218400000",
      "started_at": "2018-05-19T13:00:00+09:00",
      "hash_tag": "io18jp",
      "title": "Google I/O 報告会 2018 in 福岡",
      "event_id": 85940,
      "lon": "130.419078000000",
      "waiting": 0,
      "limit": 100,
      "owner_id": 18435,
      "owner_display_name": "kenz",
      "description": "<p>今年もGoogle I/O報告会を開催します!!</p>略",
      "address": "福岡県福岡市博多区博多駅中央街8-1 JRJP博多ビル12F",
      "catch": "",
      "accepted": 77,
      "ended_at": "2018-05-19T18:00:00+09:00",
      "place": "LINE Fukuoka株式会社 カフェスペース"
    }
  ],
  "results_start": 1,
  "results_available": 412
}

これを変換すると一発で以下を生成してくれる

data class Events(
    val results_returned: Int,
    val events: List<Event>,
    val results_start: Int,
    val results_available: Int
)

data class Event(
    val event_url: String,
    val event_type: String,
    val owner_nickname: String,
    val series: Series,
    val updated_at: String,
    val lat: String,
    val started_at: String,
    val hash_tag: String,
    val title: String,
    val event_id: Int,
    val lon: String,
    val waiting: Int,
    val limit: Int,
    val owner_id: Int,
    val owner_display_name: String,
    val description: String,
    val address: String,
    val catch: String,
    val accepted: Int,
    val ended_at: String,
    val place: String
)

data class Series(
    val url: String,
    val id: Int,
    val title: String
)

あとは

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val adapter = moshi.adapter(Events::class.java)
val res = adapter.fromJson(result)

のようにすればres.results_returnedとかres.events.forEachとか取得できる。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away