【问题标题】:JsonDecodingException: Polymorphic serializer was not found for missing class discriminatorJsonDecodingException:找不到缺少类鉴别器的多态序列化程序
【发布时间】:2023-01-10 22:31:10
【问题描述】:

我正在使用我制作的服务器来制作应用程序。获取数据时,我收到此消息时崩溃:

JsonDecodingException:找不到缺少类鉴别器的多态序列化程序('null')

这就是我的 Json 的样子(一项):

{"status":"success","data":{"books":[{"_id":"63a6e4943732ca7a52d7e135","title":"Why People Believe Weird Things: Pseudoscience, Superstition, and Other Confusions of Our Time","author":"Michael Shermer","pages":384,"imageUrl":"https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1312054576i/89281.jpg","rating":3.87,"description":"In this age of supposed scientific enlightenment, many people still believe in mind reading, past-life regression theory, New Age hokum, and alien abduction. A no-holds-barred assault on popular superstitions and prejudices, with more than 80,000 copies in print, Why People Believe Weird Things debunks these nonsensical claims and explores the very human reasons people find otherworldly phenomena, conspiracy theories, and cults so appealing. In an entirely new chapter, Why Smart People Believe in Weird Things, Michael Shermer takes on science luminaries like physicist Frank Tippler and others, who hide their spiritual beliefs behind the trappings of science. Shermer, science historian and true crusader, also reveals the more dangerous side of such illogical thinking, including Holocaust denial, the recovered-memory movement, the satanic ritual abuse scare, and other modern crazes. Why People Believe Strange Things is an eye-opening resource for the most gullible among us and those who want to protect them.","genres":["Science","Nonfiction","Psychology"],"downloadLink":"https://www.pdfdrive.com/download.pdf?id=157312261&h=00c5f6027cb74055e5b0471a9338fe9c&u=cache&ext=pdf","__v":0}

如果可能的话,我怎么能停止使数据成为多态的呢?

如果不是,我怎么能从应用程序解决这个错误?我尝试用@Polymorphic 注解对数据类进行注解,但并没有解决问题。

接口:

interface BookerlyApi {

@GET("/api/v1/books")
suspend fun getBooks():Flow<Data>

@GET("api/v1/books")
suspend fun getBook(@Query("id") id:String): Flow<Book>


suspend fun getBooksByCategory(category:String):Flow<Data>

}

注射:

    private val json = Json {
    ignoreUnknownKeys = true
}


@Singleton
@Provides
fun provideRetrofitInstance(okHttp: OkHttpClient): Retrofit {
    val contentType = "application/json".toMediaType()
    return Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(json.asConverterFactory(contentType))
        .client(okHttp)
        .build()
}

数据类:

@Serializable
@Polymorphic
data class Data(
    @SerialName("books")
    val books: List<Book>
)


@Serializable
@Polymorphic
data class Books(
    @SerialName("data")
    val `data`: Data,
    @SerialName("status")
    val status: String
)


@Serializable
@Polymorphic
data class Book(
    @SerialName("author")
    val author: String,
    @SerialName("description")
    val description: String,
    @SerialName("downloadLink")
    val downloadLink: String,
    @SerialName("genres")
    val genres: List<String>,
    @SerialName("_id")
    val id: String,
    @SerialName("imageUrl")
    val imageUrl: String,
    @SerialName("pages")
    val pages: Int,
    @SerialName("rating")
    val rating: Double,
    @SerialName("title")
    val title: String,
    @SerialName("__v")
    val v: Int
)

【问题讨论】:

    标签: json kotlin kotlinx.serialization


    【解决方案1】:

    我不知道这是否只是一个复制粘贴问题,但您粘贴的 JSON 无效,因为它缺少几个括号。正确的 JSON 是:

    {
      "status": "success",
      "data": {
        "books": [
          {
            "_id": "63a6e4943732ca7a52d7e135",
            "title": "Why People Believe Weird Things: Pseudoscience, Superstition, and Other Confusions of Our Time",
            "author": "Michael Shermer",
            "pages": 384,
            "imageUrl": "https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1312054576i/89281.jpg",
            "rating": 3.87,
            "description": "In this age of supposed scientific enlightenment, many people still believe in mind reading, past-life regression theory, New Age hokum, and alien abduction. A no-holds-barred assault on popular superstitions and prejudices, with more than 80,000 copies in print, Why People Believe Weird Things debunks these nonsensical claims and explores the very human reasons people find otherworldly phenomena, conspiracy theories, and cults so appealing. In an entirely new chapter, Why Smart People Believe in Weird Things, Michael Shermer takes on science luminaries like physicist Frank Tippler and others, who hide their spiritual beliefs behind the trappings of science. Shermer, science historian and true crusader, also reveals the more dangerous side of such illogical thinking, including Holocaust denial, the recovered-memory movement, the satanic ritual abuse scare, and other modern crazes. Why People Believe Strange Things is an eye-opening resource for the most gullible among us and those who want to protect them.",
            "genres": [
              "Science",
              "Nonfiction",
              "Psychology"
            ],
            "downloadLink": "https://www.pdfdrive.com/download.pdf?id=157312261&h=00c5f6027cb74055e5b0471a9338fe9c&u=cache&ext=pdf",
            "__v": 0
          }
        ]
      }
    }
    

    一旦你改变了它,你必须改变你的BookerlyApi接口,因为第一个和最后一个方法应该返回Flow&lt;Books&gt;。这是因为 Data 只是内部对象,即与键 data 关联的对象。

    以下示例可以正常工作:

    fun main() {
        val rawJson =
            """{
          "status": "success",
          "data": {
            "books": [
              {
                "_id": "63a6e4943732ca7a52d7e135",
                "title": "Why People Believe Weird Things: Pseudoscience, Superstition, and Other Confusions of Our Time",
                "author": "Michael Shermer",
                "pages": 384,
                "imageUrl": "https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1312054576i/89281.jpg",
                "rating": 3.87,
                "description": "In this age of supposed scientific enlightenment, many people still believe in mind reading, past-life regression theory, New Age hokum, and alien abduction. A no-holds-barred assault on popular superstitions and prejudices, with more than 80,000 copies in print, Why People Believe Weird Things debunks these nonsensical claims and explores the very human reasons people find otherworldly phenomena, conspiracy theories, and cults so appealing. In an entirely new chapter, Why Smart People Believe in Weird Things, Michael Shermer takes on science luminaries like physicist Frank Tippler and others, who hide their spiritual beliefs behind the trappings of science. Shermer, science historian and true crusader, also reveals the more dangerous side of such illogical thinking, including Holocaust denial, the recovered-memory movement, the satanic ritual abuse scare, and other modern crazes. Why People Believe Strange Things is an eye-opening resource for the most gullible among us and those who want to protect them.",
                "genres": [
                  "Science",
                  "Nonfiction",
                  "Psychology"
                ],
                "downloadLink": "https://www.pdfdrive.com/download.pdf?id=157312261&h=00c5f6027cb74055e5b0471a9338fe9c&u=cache&ext=pdf",
                "__v": 0
              }
            ]
          }
        }"""
    
        val format = Json { ignoreUnknownKeys = true }
        val decoded = format.decodeFromString<Books>(rawJson)
        println(decoded)
    }
    
    @Serializable
    data class Data(
        val books: List<Book>
    )
    
    
    @Serializable
    data class Books(
        val `data`: Data,
        val status: String
    )
    
    
    @Serializable
    data class Book(
        val author: String,
        val description: String,
        val downloadLink: String,
        val genres: List<String>,
        @SerialName("_id")
        val id: String,
        val imageUrl: String,
        val pages: Int,
        val rating: Double,
        val title: String,
        @SerialName("__v")
        val v: Int
    )
    

    它打印:

    Books(data=Data(books=[Book(author=Michael Shermer, description=In this age of supposed scientific enlightenment, many people still believe in mind reading, past-life regression theory, New Age hokum, and alien abduction. A no-holds-barred assault on popular superstitions and prejudices, with more than 80,000 copies in print, Why People Believe Weird Things debunks these nonsensical claims and explores the very human reasons people find otherworldly phenomena, conspiracy theories, and cults so appealing. In an entirely new chapter, Why Smart People Believe in Weird Things, Michael Shermer takes on science luminaries like physicist Frank Tippler and others, who hide their spiritual beliefs behind the trappings of science. Shermer, science historian and true crusader, also reveals the more dangerous side of such illogical thinking, including Holocaust denial, the recovered-memory movement, the satanic ritual abuse scare, and other modern crazes. Why People Believe Strange Things is an eye-opening resource for the most gullible among us and those who want to protect them., downloadLink=https://www.pdfdrive.com/download.pdf?id=157312261&h=00c5f6027cb74055e5b0471a9338fe9c&u=cache&ext=pdf, genres=[Science, Nonfiction, Psychology], id=63a6e4943732ca7a52d7e135, imageUrl=https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1312054576i/89281.jpg, pages=384, rating=3.87, title=Why People Believe Weird Things: Pseudoscience, Superstition, and Other Confusions of Our Time, v=0)]), status=success)
    

    另请注意,大多数属性不需要 @SerialName,因为 Kotlinx 序列化将使用属性名称 by default

    【讨论】:

      猜你喜欢
      • 2022-08-20
      • 2021-06-15
      • 2020-09-15
      • 2021-01-05
      • 1970-01-01
      • 2020-09-11
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多