gpt4 book ai didi

kotlin - 如何在 Kotlin 中解析以下 Json 数据?

转载 作者:行者123 更新时间:2023-12-01 19:45:24 25 4
gpt4 key购买 nike

我需要解析这些信息-

[
{
"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"
}]

如您所见,第一个字段不同,如何在 Kotlin 中以不同方式解析以下信息和第一个字段。

我将第一部分解析为-
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
**/


}
}

并且我也在此处使用 KLAXON 库。

最佳答案

对于您的 json,这应该有效:

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)

但这种方式非常冗长且没有必要。我建议使用像 GSON 这样的对象映射库或 Moshi .

为此,您的 json 中的视频列表理想情况下应该是这样的:
[
{
"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"
}
]
}
]

使用这个 Json,你可以很容易地为这个对象创建一个类,例如
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)

并像这样轻松解析它们:
    Moshi.Builder().build().adapter(Artist::class.java).fromJson(response)

然后访问这些信息,如:
    val artist = Moshi.Builder().build().adapter(Artist::class.java).fromJson(response)

intent.putExtra("firstArtist",artist?.name)
intent.putExtra("firstImage",artist?.image)

关于kotlin - 如何在 Kotlin 中解析以下 Json 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52033814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com