web-dev-qa-db-ja.com

KotlinでGsonを使用してJSON配列を解析する

KotlinでJSON配列を解析しようとして、単一のJSONオブジェクトからWeatherObjectオブジェクトに機能するようにしました(以下のコードスニペット)

{
"coord": {
    "lon": -2.93,
    "lat": 43.26
},

"weather": [{
    "id": 802,
    "main": "Clouds",
    "description": "scattered clouds",
    "icon": "03d"
}],

"main": {
    "temp": 283.681,
    "temp_min": 283.681,
    "temp_max": 283.681,
    "pressure": 991.72,
    "sea_level": 1034.92,
    "grnd_leve": 991.72,
    "humidity": 98
},
"wind": {
    "speed": 1.07,
    "deg": 144.001
},

"dt": 1429773245,
"id": 3128026,
"name": "Bilbao",
"cod": 200

}

ただし、JSONが同じJSONオブジェクトの配列である場合、同じことを行う方法はわかりません。

json配列[{}、{}…]からArrayList <WeatherObject>へ

何かのようなもの:

fun getWeatherObjectArrayFromJson(jsonStr: String): ArrayList&lt;WeatherObject &gt

gsonBuilder.registerTypeAdapter(ArrayList <WeatherObject&gt :: class.Java、WeatherDeserializer())に問題がある

class WeatherObject {

    var main: String = ""
    var description: String = ""
    var temp: Float = 0.0f
    var tempMax: Float = 0.0f
    var tempMin: Float = 0.0f
    var humidity: Int = 0
    var wind: WindObject? = null

}

class WeatherDeserializer : JsonDeserializer<WeatherObject> {

    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): WeatherObject? {
        val jsonObj = json as JsonObject

        val wheather = WeatherObject()
        val wind = WindObject()

        val jsonWeatherArray = jsonObj.getAsJsonArray("weather").get(0)
        val jsonMainObj = jsonObj.getAsJsonObject("main")
        val jsonWindObj = jsonObj.getAsJsonObject("wind")

        wheather.main = jsonWeatherArray.asJsonObject.get("main").asString
        wheather.description = jsonWeatherArray.asJsonObject.get("description").asString
        wheather.temp = jsonMainObj.get("temp").asFloat
        wheather.tempMax = jsonMainObj.get("temp_max").asFloat
        wheather.tempMin = jsonMainObj.get("temp_min").asFloat
        wheather.humidity = jsonMainObj.get("humidity").asInt
        wind.speed = jsonWindObj.get("speed").asFloat
        wind.deg = jsonWindObj.get("deg").asFloat
        wheather.wind = wind

        return wheather

    }
}

fun getWeatherObjectFromJson(jsonStr: String): WeatherObject {

        var stringReader: StringReader = StringReader(jsonStr)
        var jsonReader: JsonReader = JsonReader(stringReader)

        val gsonBuilder = GsonBuilder().serializeNulls()
        gsonBuilder.registerTypeAdapter(WeatherObject::class.Java, WeatherDeserializer())
        val gson = gsonBuilder.create()

        val weather: WeatherObject = gson.fromJson(jsonReader, WeatherObject::class.Java)

        return weather
    }

更新:

iT IS WORKING!テストjson配列データと関数をここに入れてください。

試した

fun getWeatherObjectFromJsonArray(jsonArrayStr: String): List<WeatherObject> {

        var stringReader: StringReader = StringReader(jsonStr)
        //var jsonReader: JsonReader = JsonReader(stringReader)

        val gsonBuilder = GsonBuilder().serializeNulls()
        gsonBuilder.registerTypeAdapter(WeatherObject::class.Java, WeatherDeserializer())
        val gson = gsonBuilder.create()

        val weatherList: List<WeatherObject> = gson.fromJson(stringReader , Array<WeatherObject>::class.Java).toList()
        //val weatherList: List<WeatherObject> = gson.fromJson(jsonReader, Array<WeatherObject>::class.Java).toList

        return weatherList
    }

で例外を得た

val weatherList: List<WeatherObject> = gson.fromJson(stringReader , Array<WeatherObject>::class.Java).toList()

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

jSON配列データは次のようになります。

[
{
  "coord": {
    "lon": -2.93,
    "lat": 43.26
  },

  "weather": [{
    "id": 802,
    "main": "Clouds",
    "description": "scattered clouds",
    "icon": "03d"
  }],

  "main": {
    "temp": 283.681,
    "temp_min": 283.681,
    "temp_max": 283.681,
    "pressure": 991.72,
    "sea_level": 1034.92,
    "grnd_leve": 991.72,
    "humidity": 98
  },
  "wind": {
    "speed": 1.07,
    "deg": 144.001
  },
  "clouds": {
    "all": 36
  },
  "dt": 1429773245,
  "id": 3128026,
  "name": "Bilbao",
  "cod": 200
}, 

{
  "coord": {
    "lon": -2.93,
    "lat": 43.26
  },

  "weather": [{
    "id": 802,
    "main": "Clouds",
    "description": "scattered clouds",
    "icon": "03d"
  }],

  "main": {
    "temp": 283.681,
    "temp_min": 283.681,
    "temp_max": 283.681,
    "pressure": 991.72,
    "sea_level": 1034.92,
    "grnd_leve": 991.72,
    "humidity": 98
  },
  "wind": {
    "speed": 1.07,
    "deg": 144.001
  },
  "clouds": {
    "all": 36
  },
  "dt": 1429773245,
  "id": 3128026,
  "name": "Bilbao",
  "cod": 200
}
]
22
lannyf

次のようにfromJson()関数呼び出しのパラメーターを変更する必要があります。

_val weatherList: List<WeatherObject> = gson.fromJson(stringReader , Array<WeatherObject>::class.Java).toList()
_

クラス型に_Array<WeatherObject>::class.Java_を渡してから、結果をListに変換する必要があります。 registerTypeAdapter()関数呼び出しを変更する必要はありません。

次のコードを確認してください。

_fun getWeatherObjectFromJson(jsonStr: String): List<WeatherObject> {

        var stringReader: StringReader = StringReader(jsonStr)
        var jsonReader: JsonReader = JsonReader(stringReader)

        val gsonBuilder = GsonBuilder().serializeNulls()
        gsonBuilder.registerTypeAdapter(WeatherObject::class.Java, WeatherDeserializer())
        val gson = gsonBuilder.create()

       val weatherList: List<WeatherObject> = gson.fromJson(stringReader , Array<WeatherObject>::class.Java).toList()

        return weatherList
    }
_
40
chandil03