I need to parse this information-
[
{
"artist": "12",
"image": "23"
},
{
"video_id": "12",
"video_title": "23"
},
{
"video_id": "12",
"video_title": "23"
},
{
"video_id": "12",
"video_title": "23"
},
{
"video_id": "12",
"video_title": "23"
},
{
"video_id": "12",
"video_title": "23"
}]
As you can see the first field is different, how to parse below information differently and the first field differently in Kotlin.
I am parsing 1st part as-
response ->
for (i in 0..(response.length() -1)){
/**
FIRST SONG
**/
val song = response.get(0).toString()
val listOfSongs = response.toString()
val parser = Parser()
val stringBuilder = StringBuilder(song)
val json: JsonObject = parser.parse(stringBuilder) as JsonObject
val firstArtist = json.string("artist")
val firstImage = json.string("image")
val intent = Intent(activity,ResultPage::class.java)
intent.putExtra("firstArtist",firstArtist)
intent.putExtra("firstImage",firstImage)
startActivity(intent)
/**
FIRST SONG
**/
}
}
and am also using KLAXON library here.
For your json, this should work :
fun parseResponse(response: String) {
var artist = ""
var image = ""
val videoList = ArrayList<Video>()
val jsonArray = JSONArray(response)
(0..5).forEach { index ->
val jsonObject = jsonArray.getJSONObject(index)
if (jsonObject.has("artist") && jsonObject.has("image")) {
artist = jsonObject.getString("artist")
image = jsonObject.getString("image")
}
else if (jsonObject.has("video_id") && jsonObject.has("video_title")) {
val newVideo = Video(jsonObject.getString("video_id"), jsonObject.getString("video_title"))
videoList.add(newVideo)
}
}
}
class Video(val id: String, val title: String)
But this way is very lengthy and unnecessary. I would suggest use an Object Mapping library like GSON or Moshi.
For that, the video list in your json should ideally be something like:
[
{
"artist": "12",
"image": "23",
"videos": [
{
"video_id": "12",
"video_title": "23"
},
{
"video_id": "12",
"video_title": "23"
},
{
"video_id": "12",
"video_title": "23"
},
{
"video_id": "12",
"video_title": "23"
},
{
"video_id": "12",
"video_title": "23"
}
]
}
]
Using this Json, you can easily create a class for this object, e.g.
class Artist(val id: String, val name: String, val image: String, val videos: List<Video>)
class Video(@field:Json(name = "video_id") val id: String, @field:Json(name = "video_title") val title: String)
And parse them easily like this:
Moshi.Builder().build().adapter(Artist::class.java).fromJson(response)
and then access this information like:
val artist = Moshi.Builder().build().adapter(Artist::class.java).fromJson(response)
intent.putExtra("firstArtist",artist?.name)
intent.putExtra("firstImage",artist?.image)