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

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 148 path $.main

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

我使用 retrofit 来解析 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 响应生成的数据 class 不正确。许多东西都是对象,但您已将其分配为 List 项。这是基于您的 JSON 的正确数据 class 响应。所以 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 id: Int,
    val sunrise: Int,
    val sunset: Int,
    val type: Int
)

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

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

我建议你尝试使用这个再试一次。这里还有一个根据JSON自动生成数据classes的插件。它可能对您有更多帮助。

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