I was working with Moshi to pull JSON data from an API and map it to my DTO Data classes when I encountered this error:
FATAL EXCEPTION: main Process: com.plcoding.weatherapp, PID: 9706 com.squareup.moshi.JsonDataException: Required value 'weatherData' missing at $ at com.squareup.moshi.internal.Util.missingProperty(Util.java:649) at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapter.fromJson(KotlinJsonAdapter.kt:103) at com.squareup.moshi.internal.NullSafeJsonAdapter.fromJson(NullSafeJsonAdapter.java:41)
My DTO are annotated with @field:Json(name = "xyz")
@JsonClass(generateAdapter = true)
data class WeatherDataDTO(
@field:Json(name = "time")
val times: List<String>,
@field:Json(name = "temperature_2m")
val temperatures: List<Double>)
I have enclosed the above DTO in another DTO.
JsonClass(generateAdapter = true)
data class WeatherDTO(
@field:Json(name = "hourly")
val weatherData: WeatherDataDTO
)
I am using the latest Retrofit
and Moshi
Libs on Kotlin 1.6.10
// Retrofit, Core Moshi JSON Library and Moshi's Kotlin support and converter factory
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation "com.squareup.moshi:moshi:1.12.0"
implementation "com.squareup.moshi:moshi-kotlin:1.12.0"
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
My Json endpoint looks this:
{
"latitude": 42,
"longitude": 36,
"generationtime_ms": 0.3489255905151367,
"hourly": {
"time": [],
"temperature_2m": []
.....
}
Have struggled with this error for days but cannot find a solution.
Removing @field:Json()
in favor of just @Json(name = "xyz")
did the trick for me.
My DTO now looks like this and is working fine!
@JsonClass(generateAdapter = true)
data class WeatherDataDTO(
@Json(name = "time")
val times: List<String>,
@Json(name = "temperature_2m")
val temperatures: List<Double>)
Edit
Also, check the error for the required value.
For instance, the Json name was @Json(name = "name")
but I had accidentally renamed it to @Json(name = "cityName")
.
This also causes the same exception.
For more info on @field:Json(name = "xyz")
vs @Json(name = "xyz")
you can review this StackOverflow question.
I also found this article to be helpful in case the Moshi-JSON Exception persists.
Happy Coding ...