Skip to content
Advertisement

Can I apply a custom deserializer to within another custom deserializer for GSON

The below is a working code that helps to convert JSON in Object accordingly. If the String is nil, it will be treated as null.

There’s 2 custom deserializer i.e. MyOwnStringDeserializer and MyOwnListDeserializer. I am not happy with MyOwnListDeserializer deserializer, as essentially what it is doing is in term of the String comparison to the rule defined in MyOwnStringDeserializer. But I just can’t and don’t know how to apply the MyOwnStringDeserializer into MyOwnListDeserializer.

Is there a way for me to do so, that simplify the MyOwnListDeserializer? Or even better if there’s a way to use just a single custom deserializer and could still achieve the same result?

JavaScript

Advertisement

Answer

The method you’re looking for is JsonDeserializationContext.deserialize(). Per the warning about how to cause an infinite loop, this invokes any relevant custom deserializers you’ve set up.

I believe replacing the initialization of subItems inside the loop with a one-liner MySubItems subItems = context.deserialize(element, MySubItems.class); will do the trick, leaving only that and the check around list.add(subItems) in the loop body.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement