使用Moshi进行Retrofit调用没有得到结果



我是API界的新手。在试图使用Retrofit和Moshi获取API时,看起来我得到了0个结果,我不应该这样做。谁能告诉我我做错了什么设置?

编辑:在进一步的调查,我实际上得到这个错误在视图模型,我调用API:

Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $

我要取的API:

https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2021-01-01&endtime=2021-08-24&minmagnitude=4&latitude=24.0162182&longitude=90.6402874&maxradiuskm=400

这是我的Retrofit和Moshi设置:

private const val BASE_URL = "https://earthquake.usgs.gov/"
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
interface UsgsApiService {
@GET("fdsnws/event/1/query")
suspend fun getQuakes(
@Query("format") format: String = "geojson",
@Query("starttime") starttime: String = "2021-01-01",
@Query("endtime") endtime: String = "2021-08-24",
@Query("minmagnitude") minmagnitude: String = "4",
@Query("latitude") latitude: String = "24.0162182",
@Query("longitude") longitude: String = "90.6402874",
@Query("maxradiuskm") maxradiuskm: String = "400"
): List<Quake>
}
object UsgsApi {
val retrofitService: UsgsApiService by lazy {
retrofit.create(UsgsApiService::class.java)
}
}
这是我的模型:
@JsonClass(generateAdapter = true)
data class Quake(
@Json(name = "features")
val features: List<Feature>
)
@JsonClass(generateAdapter = true)
data class Feature(
@Json(name = "id")
val id: String,
@Json(name = "properties")
val properties: Properties,
@Json(name = "geometry")
val geometry: Geometry
)
@JsonClass(generateAdapter = true)
data class Properties(
@Json(name = "mag")
val mag: Double?,
@Json(name = "place")
val place: String,
@Json(name = "time")
val time: Long,
@Json(name = "url")
val url: String
)
@JsonClass(generateAdapter = true)
data class Geometry(
@Json(name = "coordinates")
val coordinates: List<Double>
)

谢谢你的帮助!

API没有返回json数组,但您试图解析为List<>类型。

API返回的似乎是一个GeoJSON featurecall对象,在其features属性中具有地震数组,因此您的顶级json模型类应该至少可以提取features数组。

最新更新