【问题标题】:Gson deserialization of optional+nullable value可选+可空值的Gson反序列化
【发布时间】:2021-01-12 18:21:38
【问题描述】:

从this link得到的以下文字完美地描述了我要解决的问题:

有关何时有用的具体示例,请考虑支持对象部分更新的 API。使用此 API,JSON 对象将用于为某些长期存在的对象传递补丁。任何包含的属性都指定应更新对象的相应值,而任何省略的属性的值应保持不变。如果对象的任何属性可以为空,则为属性发送的 null 值与缺少的属性根本不同,因此必须区分这些情况。

那篇文章提出了一个解决方案,但使用 kotlinx.serialization 库,但是,我现在必须使用 gson 库。

所以我正在尝试实施自己的解决方案,因为我没有找到任何适合我的用例的东西(如果有,请告诉我)。

data class MyObject(
    val fieldOne: OptionalProperty<String> = OptionalProperty.NotPresent,
    val fieldTwo: OptionalProperty<String?> = OptionalProperty.NotPresent,
    val fieldThree: OptionalProperty<Int> = OptionalProperty.NotPresent
)

fun main() {
    val gson = GsonBuilder()
        .registerTypeHierarchyAdapter(OptionalProperty::class.java, OptionalPropertyDeserializer())
        .create()
    val json1 = """{
            "fieldOne": "some string",
            "fieldTwo": "another string",
            "fieldThree": 18
        }
        """
    println("json1 result object: ${gson.fromJson(json1, MyObject::class.java)}")
    val json2 = """{
            "fieldOne": "some string",
            "fieldThree": 18
        }
        """
    println("json2 result object: ${gson.fromJson(json2, MyObject::class.java)}")
    val json3 = """{
            "fieldOne": "some string",
            "fieldTwo": null,
            "fieldThree": 18
        }
        """
    println("json3 result object: ${gson.fromJson(json3, MyObject::class.java)}")

}

sealed class OptionalProperty<out T> {

    object NotPresent : OptionalProperty<Nothing>()

    data class Present<T>(val value: T) : OptionalProperty<T>()
}

class OptionalPropertyDeserializer : JsonDeserializer<OptionalProperty<*>> {

    private val gson: Gson = Gson()

    override fun deserialize(
        json: JsonElement?,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): OptionalProperty<*> {
        println("Inside OptionalPropertyDeserializer.deserialize json:$json")
        return when {
            // Is it a JsonObject? Bingo!
            json?.isJsonObject == true ||
                    json?.isJsonPrimitive == true-> {

                // Let's try to extract the type in order
                // to deserialize this object
                val parameterizedType = typeOfT as ParameterizedType

                // Returns an Present with the value deserialized
                return OptionalProperty.Present(
                    context?.deserialize<Any>(
                        json,
                        parameterizedType.actualTypeArguments[0]
                    )!!
                )
            }
            // Wow, is it an array of objects?
            json?.isJsonArray == true -> {

                // First, let's try to get the array type
                val parameterizedType = typeOfT as ParameterizedType

                // check if the array contains a generic type too,
                // for example, List<Result<T, E>>
                if (parameterizedType.actualTypeArguments[0] is WildcardType) {

                    // In case of yes, let's try to get the type from the
                    // wildcard type (*)
                    val internalListType = (parameterizedType.actualTypeArguments[0] as WildcardType).upperBounds[0] as ParameterizedType

                    // Deserialize the array with the base type Any
                    // It will give us an array full of linkedTreeMaps (the json)
                    val arr = context?.deserialize<Any>(json, parameterizedType.actualTypeArguments[0]) as ArrayList<*>

                    // Iterate the array and
                    // this time, try to deserialize each member with the discovered
                    // wildcard type and create new array with these values
                    val result = arr.map { linkedTreeMap ->
                        val jsonElement = gson.toJsonTree(linkedTreeMap as LinkedTreeMap<*, *>).asJsonObject
                        return@map context.deserialize<Any>(jsonElement, internalListType.actualTypeArguments[0])
                    }

                    // Return the result inside the Ok state
                    return OptionalProperty.Present(result)
                } else {
                    // Fortunately it is a simple list, like Array<String>
                    // Just get the type as with a JsonObject and return an Ok
                    return OptionalProperty.Present(
                        context?.deserialize<Any>(
                            json,
                            parameterizedType.actualTypeArguments[0]
                        )!!
                    )
                }
            }
            // It is not a JsonObject or JsonArray
            // Let's returns the default state NotPresent.
            else -> OptionalProperty.NotPresent
        }
    }

}

我从here 获得了自定义反序列化器的大部分代码。

这是我运行main 函数时的输出:

Inside OptionalPropertyDeserializer.deserialize json:"some string"
Inside OptionalPropertyDeserializer.deserialize json:"another string"
Inside OptionalPropertyDeserializer.deserialize json:18
json1 result object: MyObject(fieldOne=Present(value=some string), fieldTwo=Present(value=another string), fieldThree=Present(value=18))
Inside OptionalPropertyDeserializer.deserialize json:"some string"
Inside OptionalPropertyDeserializer.deserialize json:18
json2 result object: MyObject(fieldOne=Present(value=some string), fieldTwo=my.package.OptionalProperty$NotPresent@573fd745, fieldThree=Present(value=18))
Inside OptionalPropertyDeserializer.deserialize json:"some string"
Inside OptionalPropertyDeserializer.deserialize json:18
json3 result object: MyObject(fieldOne=Present(value=some string), fieldTwo=null, fieldThree=Present(value=18))

我正在测试 fieldTwo 的不同选项,它几乎可以完全正常工作,除了第 3 个 json,我希望 fieldTwo 应该是 fieldTwo=Present(value=null) 而不是 fieldTwo=null。

我看到在这种情况下,自定义反序列化器甚至没有被调用 fieldTwo。

谁能发现我在这里缺少的东西?任何提示将不胜感激!

【问题讨论】:

    标签: json kotlin gson


    【解决方案1】:

    我最终放弃了 gson 并搬到了 moshi。

    我根据this comment 中提出的解决方案实现了此行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      相关资源
      最近更新 更多