简体   繁体   English

改造:解析json时遇到麻烦

[英]Retrofit: trouble parsing json

After doing some tutorials iam trying to use a specific API but my POJO always get null object, what is the correct way to parse the data inside "results" key?在做了一些教程之后,我尝试使用特定的 API,但我的 POJO 总是得到空对象,解析“结果”键中的数据的正确方法是什么?

  "success": true,
  "metadata": {
    "sort": "POPULARITY",
    "total_products": 20,
    "title": "Phones & Tablets",
    "results": [
      {
        "sku": "1",
        "name": "Samsung Galaxy S9",
        "brand": "Samsung",
        "max_saving_percentage": 30,
        "price": 53996,
        "special_price": 37990,
        "image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
        "rating_average": 5
      },`
``

If you are using Retrofit and Gson如果你正在使用 Retrofit 和 Gson

You can have the following POJOs您可以拥有以下 POJO

data class APIReponse(
    val success: Boolean,
    val metadata: Metadata
)

data class Metadata(
    val sort: String,
    val total_products: Int,
    val title: String,
    val results: List<Product>
)

data class Product(
    val sku: Int,
    val name: String,
    val brand: String,
    val max_saving_percentage: Int,
    val price: Int,
    val special_price: Int,
    val image: String,
    val rating_average: String
)

For more information on using Gson on Retrofit please check https://square.github.io/retrofit/有关在 Retrofit 上使用 Gson 的更多信息,请查看https://square.github.io/retrofit/

I hope that gives you a little idea.我希望这能给你一些想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM