Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

json - Gson deserialization of optional+nullable value

The problem I am trying to solve is perfectly described by the following text got from this link:

For a concrete example of when this could be useful, consider an API that supports partial updates of objects. Using this API, a JSON object would be used to communicate a patch for some long-lived object. Any included property specifies that the corresponding value of the object should be updated, while the values for any omitted properties should remain unchanged. If any of the object’s properties are nullable, then a value of null being sent for a property is fundamentally different than a property that is missing, so these cases must be distinguished.

That post presents a solution but using the kotlinx.serialization library, however, I must use gson library for now.

So I am trying to implement my own solution as I didn't find anything that could suit my use case (please let me know if there is).

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
        }
    }

}

I got most of the code for the custom deserializer from here.

This is the output when I run the main function:

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))

I am testing the different options for the fieldTwo and it is almost fully working, with the exception of the 3rd json, where I would expect that fieldTwo should be fieldTwo=Present(value=null) instead of fieldTwo=null.

And I see that in this situation, the custom deserializer is not even called for fieldTwo.

Can anyone spot what I am missing here? Any tip would be very appreciated!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I ended giving up of gson and move to moshi.

I implemented this behavior based on the solution presented in this comment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...