微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期为 BEGIN_ARRAY 但在第 1 行第 148 列路径 $.main 处为 BEGIN_OBJECT

如何解决com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期为 BEGIN_ARRAY 但在第 1 行第 148 列路径 $.main 处为 BEGIN_OBJECT

我有问题,真的不知道如何解决这个问题。找了几天类似的帖子,没找到。

我使用改造来解析api并将其放入房间数据库并使用rxjava3 因为它将是异步的

那是我的 JSON

{
  "coord": {
    "lon": -0.1257,"lat": 51.5085
  },"weather": [
    {
      "id": 803,"main": "Clouds","description": "broken clouds","icon": "04d"
    }
  ],"base": "stations","main": {
    "temp": 22.78,"feels_like": 22.81,"temp_min": 21.23,"temp_max": 23.92,"pressure": 1020,"humidity": 65
  },"visibility": 10000,"wind": {
    "speed": 0.45,"deg": 264,"gust": 2.68
  },"clouds": {
    "all": 75
  },"dt": 1623415339,"sys": {
    "type": 2,"id": 2019646,"country": "GB","sunrise": 1623383015,"sunset": 1623442617
  },"timezone": 3600,"id": 2643743,"name": "London","cod": 200
}

API 服务

interface OpenWeatherApiService {

@GET("weather")
fun getCurrentWeather(
    @Query("q") location:String,@Query("appid") key:String,@Query("units") units:String,@Query("lang") language:String = "en"
):Observable<CurrentWeatherResponse>}

那是我的应用模块

@Module
@InstallIn(ActivityComponent::class)
object AppModule {
@Provides
fun provideOkHttpClient() =if(BuildConfig.DEBUG) {
    val interceptor = HttpLoggingInterceptor()
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
    OkHttpClient
        .Builder()
        .addInterceptor(interceptor)
        .build()
}else{
    OkHttpClient
        .Builder()
        .build()
}
@Provides
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit = Retrofit.Builder()
    .baseUrl("https:/api.openweathermap.org/data/2.5/")
    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build()

@Provides
fun provideGson(): Gson = GsonBuilder().create()

@Provides
fun provideOpenWeatherApiService(retrofit: Retrofit):OpenWeatherApiService = retrofit.create(OpenWeatherApiService::class.java)

@Provides
fun provideOpenWeatherApiHelper(openWeatherApiHelper: OpenWeatherApiHelperImpl):OpenWeatherApiHelper = openWeatherApiHelper

@Provides
fun provideForecastDatabase(@ApplicationContext appContext: Context) = ForecastDatabase.getDatabase(appContext)

@Provides
fun provideCurrentWeatherDao(db: ForecastDatabase) = db.currentWeatherDao()


}

我的回复

const val CURRENT_WEATHER_ID = 0

@Entity(tableName = "current_weather")
data class CurrentWeatherResponse(
        val main: List<Main>,val name: String? = "",val visibility: Int? = 0,val weather: List<Weather>,val wind:List<Wind>
){
    @PrimaryKey(autoGenerate = false)
    var id_current_weather:Int = CURRENT_WEATHER_ID
}

我的 Main 类型转换器,我把它放在数据库

class MainConverter {
    val gson = Gson()

    @TypeConverter
    fun listMainToString(mainList: List<Main?>?):String?{
        return gson.toJson(mainList)
    }
    @TypeConverter
    fun stringToListMain(dataMain:String?):List<Main?>?{
        if (dataMain ==  null){
            return Collections.emptyList()
        }
        val listType: Type = object :
                Typetoken<List<Main>?>() {}.type
        return gson.fromJson<List<Main?>?>(dataMain,listType)
    }
}

解决方法

您为 JSON 响应生成的数据类不正确。许多事物都是对象,但您已将其指定为 List 项。这是基于您的 JSON 的正确数据类响应。所以 JSON 响应没有被正确解析。

data class CurrentWeatherResponse(
    val base: String,val clouds: Clouds,val cod: Int,val coord: Coord,val dt: Int,val id: Int,val main: Main,val name: String,val sys: Sys,val timezone: Int,val visibility: Int,val weather: List<Weather>,val wind: Wind
)

data class Clouds(
    val all: Int
)

data class Coord(
    val lat: Double,val lon: Double
)

data class Main(
    val feels_like: Double,val humidity: Int,val pressure: Int,val temp: Double,val temp_max: Double,val temp_min: Double
)

data class Sys(
    val country: String,val sunrise: Int,val sunset: Int,val type: Int
)

data class Weather(
    val description: String,val icon: String,val main: String
)

data class Wind(
    val deg: Int,val gust: Double,val speed: Double
)

我建议您尝试使用此功能并重试。这里还有一个插件,可以自动生成基于 JSON 的数据类。它可能对您有更多帮助。

https://plugins.jetbrains.com/plugin/10054-generate-kotlin-data-classes-from-json

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。