On Sat, Jan 9, 2021 at 10:09 AM Govinda Sakhare
<
govindas...@gmail.com> wrote:
>
> Hi All,
>
> I have written a custom de-serializer to ensure backward compatibility between models and applied it on a field as below. I want the de-serializer to kick-in if the JsonNode is array otherwise I want the default deserializer to deserialize the field. I tried the below approach using the ObjectMapper object but it is not working.
>
> class Person {
>
> private int id;
>
> @JsonDeserialize(using = CustomDeserializer.class)
> @JsonAlias("addresses")
> private AddressDetails addressDetails;
> // .Getter setters
> }
>
> but in else part jsonNode.asText() is returning empty string, but debugger is showing child nodes. am I doing something wrong here?
Yes, the problem is that "Jsonnode.asText()" will just return String
value of scalar-valued node, and that is not going to work as input
in most cases (it might sort of work for Boolean and Number values but
nothing else): for Objects and Arrays it simply returns "".
In future you may want to read Javadocs of the methods you call to see
what they are supposed to do, that helps a lot in figuring out how to
do things.
There are couple of ways to "read" from JsonNode (like it was a json
document), however, and the simplest is:
return ((ObjectMapper) parser.getCodec()).treeToValue(jsonNode,
AddressDetails.class);
(note: you usually do not want to do this
ObjectMapper objectMapper = new ObjectMapper();
as constructing a new mapper is very expensive and does not have
configuration settings).
Hope this helps,
-+ Tatu +-