JSON is an untyped language. So you really have two scenarios here:
Situation #1: You know what types these fields should have, and you want to interact with the values in a safe manner.
In this case, you either need to hard-code the casts to the types you know should exist, or you should create a POJO class to deserialize into. (If this class is only used within a small scope, you could use a private class or even a local class inside the function that uses it.) In any case, either mapper.readValue()
or your code will throw an exception if the data doesn't match. You will need to either catch this exception or propagate to your caller. Exactly what kinds of failures are meaningful here really depends on your application, but there are numerous possible failures.
Situation #2: You have no idea what types these fields should have, and you want to discover the types of values to interact with.
Unfortunately, there is no statically-verifiable way to interact with types that will be unknown until runtime. (That's basically the definition of the distinction between static and dynamic type systems.) In practice, with data deserialized from JSON, everything will either be a Number
, String
, List<?>
, Map<?, ?>
, or null
. So you will need to deal with those cases, but even within a List
, you don't have any way to know what type each element is without looping through and examining each one -- and it's possible that the only Java type that you will be able to use to represent the list is List<?>
(that is, there may be no valid type that the wildcard can resolve to, e.g. in the case of a heterogeneous list).
That said, it's relatively uncommon to need to analyze a data structure that is truly dynamic. Usually any JSON data does have a standardized structure to it, and so the right solution is to build a data object (as a Java POJO class) that represents that structure, and then transform your incoming data into your object. If the data can't be represented in your object, then that means that the incoming data isn't something your program is prepared to handle. In most cases you should immediately abort with an error rather than trying to muddle on with data that you don't understand (this is the "fail fast" principle).