Trying to parse JSON array in Kotlin, made it work for single JSON object to a WeatherObject object (code snippet below)

{
"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

}

but not sure how to do the same if the JSON is a array of same JSON object, i.e.

从json数组[{},{}…]到ArrayList<WeatherObject>

something like:

fun getWeatherObjectArrayFromJson(jsonStr: String): ArrayList<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
    }

更新:

try 了chandil03的解决方案,成功了!将测试json数组数据和函数放在这里:

tried

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
    }

got exception at

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
}
]

推荐答案

您需要在fromJson()函数调用中更改参数,如下所示:

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

You need to pass Array<WeatherObject>::class.java for class type and then convert result into List. No need to change registerTypeAdapter() function call.

判断以下代码:

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
    }

Kotlin相关问答推荐

Kotlin中的增广赋值语句中的难以理解的错误

S使用MAP和ElseThrow的习惯用法是什么?

如何让 LocalDateTime.parse 拒绝 24:00 时间

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

Kotlin 可空泛型

在 APK META-INF/library_release.kotlin_module 中复制的重复文件

零安全的好处

在 Kotlin 中取最后 n 个元素

未在IntelliJ IDEA上运行临时文件

kotlin-bom 库是做什么的?

如何使用kotlin中的反射查找包中的所有类

TornadoFX 中设置 PrimaryStage 或 Scene 属性的方法

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

我们如何在Java注释声明中引用Kotlin常量?

spring.config.location 在 Spring Boot 2.0.0 M6 上不起作用

如何在Kotlin中使方法param可变?

通过在 kotlin-gradle 中使用子项目Unresolved reference: implementation

有没有办法在Kotlin中设置一个私有常量

Kotlin - 错误:Could not find or load main class _DefaultPackage