Reputation: 1377
I need to parse the one shown below, JSON, I use Retrofit, Moshi, Kotlin, I use the data class as a placeholder, I output the result to LogCat, but nothing is output.
{
persons:[
{
"name": "Christian",
"age": 5
},
{
"name": "Marcus",
"age": 10
},
{
"name": "Norman",
"age": 20
}
]
}
data class Persons(
@Json(name = "name") val name: String,
@Json(name = "age") val age: Int
)
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
interface PersonApiService {
@GET(ADDITIONAL_URL)
fun getPersons(): Call<Persons>
}
object PersonApi {
val retrofitService: PersonApiService by lazy {
retrofit.create(PersonApiService::class.java)
}
}
override fun onResponse(call: Call<Persons>, response: Response<Persons>) {
Log.i(TAG, "onResponse: ${response.body()}") // RETURNS NOTHING
}
Upvotes: 1
Views: 433
Reputation: 1377
Read this article and you will understand everything.
Remember and learn to distinguish between 2 types of Json: Nested JSON Object | Array of JSON Objects
Nested JSON Objecs: | Array of JSON Objects
|
{ |
persons:[ | [
{ | {
"name": "Christian", | "name": "Christian",
"age": 5 | "age": 5
}, | },
{ | {
"name": "Marcus", | "name": "Marcus",
"age": 10 | "age": 10
}, | },
{ | {
"name": "Norman", | "name": "Norman",
"age": 20 | "age": 20
} | }
] | ]
}
data class Persons(
@Json(name = "persons") val persons: List<PersonProperty>
)
data class PersonProperty(
@Json(name = "name") val name: String,
@Json(name = "age") val age: Int
)
override fun onResponse(call: Call<Persons>, response: Response<Persons>) {
Log.i(TAG, "onResponse: ${response.body()}") // RETURNS List Persons
}
Upvotes: 2