android – Check for null in JsonDeserializer

Question:

There is a json model

{"amount" : null}

If the value is equal to null necessary to return BigDecimal.ZERO

Wrote a deserializer:

class BigDecimalDeserializer : JsonDeserializer<BigDecimal> {
    override fun deserialize(json : JsonElement ?, typeOfT : Type ?, context : JsonDeserializationContext ?) : BigDecimal {

        if (json !!.isJsonNull) {
                return BigDecimal.ZERO
        }

        json ?.let {

                try {
                        json.asBigDecimal
                } catch (t : NumberFormatException) {
                        return BigDecimal.ZERO
                }

        }

        return json ?.asBigDecimal !!
    }
}

But null not caught in any condition. Tell me what the error is.

Answer:

The problem is that the deserializer does not classify your json to the BigDecimal type, but most likely perceives it as a String or something else – accordingly, it does not end up in your custom deserializer.

Scroll to Top
AllEscort