处理一个有时为布尔值且有时为int的字段 [英] Dealing with one field that is sometimes boolean and sometimes int

查看:105
本文介绍了处理一个有时为布尔值且有时为int的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用reddit JSON API.有一些帖子数据对象包含一个称为edited的字段,如果该帖子尚未被编辑,则可能为布尔值false;如果该帖子已被编辑,则可能为timestamp int.

I'm trying to work with the reddit JSON API. There are post data objects that contain a field called edited which may contain a boolean false if the post hasn't been edited, or a timestamp int if the post was edited.

有时是布尔值:

{ "edited": false, "title": "Title 1" }

{ "edited": false, "title": "Title 1" }

有时是一个int: { "edited": 1234567890, "title": "Title 2" }

Sometimes an int: { "edited": 1234567890, "title": "Title 2" }

当尝试解析POJO将字段设置为int的JSON时,出现错误:JsonDataException:期望为int但为BOOLEAN ...

When trying to parse the JSON where the POJO has the field set to int, I get an error: JsonDataException: Expected an int but was BOOLEAN...

我如何使用Moshi处理此问题?

How can I deal with this using Moshi?

推荐答案

我也遇到了类似的问题,即我的字段有时是布尔值,有时是整数.我希望他们永远是整数.这是我用Moshi和Kotlin解决的方法:

I also ran into a similar problem where I had fields that were sometimes booleans, and sometimes ints. I wanted them to always be ints. Here's how I solved it with Moshi and kotlin:

  1. 制作新的注释,以将其用于将字段从boolean转换为int的


    @JsonQualifier
    @Retention(AnnotationRetention.RUNTIME)
    @Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION)
    annotation class ForceToInt

    internal class ForceToIntJsonAdapter {
        @ToJson
        fun toJson(@ForceToInt i: Int): Int {
            return i
        }

        @FromJson
        @ForceToInt
        fun fromJson(reader: JsonReader): Int {
            return when (reader.peek()) {
                JsonReader.Token.NUMBER -> reader.nextInt()
                JsonReader.Token.BOOLEAN -> if (reader.nextBoolean()) 1 else 0
                else -> {
                    reader.skipValue() // or throw
                    0
                }
            }
        }
    }

  1. 在您要强制进行int的字段上使用此注释:

    @JsonClass(generateAdapter = true)
    data class Discovery(
            @Json(name = "id") val id: String = -1,
            @ForceToInt @Json(name = "thanked") val thanked: Int = 0
    )

这篇关于处理一个有时为布尔值且有时为int的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆