【问题标题】:How to parse json in android如何在android中解析json
【发布时间】:2021-09-06 00:35:24
【问题描述】:

https://api.mojilala.com/v1/stickers/trending?api_key=dc6zaTOxFJmzC

data class RootApi(val data : List<AllData>)
data class AllData(val images : ImageSticker)
data class ImageSticker(val fixed_height : ActualImage)
data class ActualImage(val url : String)

根据给定的 api,这是否是正确的 POJO 类

【问题讨论】:

  • 不要公开密钥,否则可能会被滥用。
  • 它是公共 API :)
  • API 是公开的,但您确定密钥吗?
  • github.com/mojilala/sticker-api 是的,它是公开的

标签: android json database retrofit rest


【解决方案1】:

首先,在问题中隐藏您的 API 密钥。即将生成 JSON 的数据类。我建议您使用以下插件

https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-

不,这不是正确的数据类。事实上,它非常大。我什至无法将其全部粘贴到答案中。使用插件。粘贴 JSON 响应并自己生成。

【讨论】:

  • 它是一个公共 API,也是免费的 :)
【解决方案2】:

按照@che10 的回答,您应该得到以下结果:

data class Data(
    // Assuming you are using Moshi https://github.com/square/moshi
    // Use @SerializedName("data") if you're using Gson
    @Json(name="data")
    val stickers: List<Sticker>,
    val meta: Meta,
    val pagination: Pagination
)

data class Sticker(
    val designer: String,
    val id: String,
    val images: Images,
    val is_animated: Boolean,
    val rating: String,
    val tags: List<String>,
    val url: String
)

data class Pagination(
    val offset: String,
    val total: Int,
    val total_count: Int
)

data class Meta(
    val msg: String,
    val status: Int
)

// Different fields but of two types so we can reuse the classes
// Difference between AnimatedImage and StillImage is the two webp fields
data class Images(
    // Animated images
    val fixed_height: AnimatedImage,
    val fixed_height_downsampled: AnimatedImage,
    val fixed_height_medium: AnimatedImage,
    val fixed_height_medium_downsampled: AnimatedImage,
    val fixed_height_small: AnimatedImage,
    val fixed_width: AnimatedImage,
    val fixed_width_downsampled: AnimatedImage,
    val fixed_width_medium: AnimatedImage,
    val fixed_width_medium_downsampled: AnimatedImage,
    val fixed_width_small: AnimatedImage,
    // Still images
    val fixed_height_still: StillImage,
    val fixed_height_medium_still: StillImage,
    val fixed_height_small_still: StillImage,
    val fixed_width_still: StillImage,
    val fixed_width_medium_still: StillImage,
    val fixed_width_small_still: StillImage,
)

data class StillImage(
    val url: String,
    val size: Int,
    val height: Int,
    val width: Int,
)

data class AnimatedImage(
    val url: String,
    val size: Int,
    val height: Int,
    val width: Int,
    val webp: String,
    val webp_size: Int
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2015-10-24
    • 2011-07-30
    • 2017-04-08
    • 2013-01-26
    相关资源
    最近更新 更多