Is there a good way to represent JSON in Java in a convenient, easy-to-use, type-safe way?
We've been doing it using Maps, Lists, and primitives. This works fine, except that we have to add a lot of checks for missing values.
Jackson has a good way of handling the problem:
JsonNode node;
// returns MissingNode if name not present, no null check required
node.path("name").asText();
Jackson's syntax is uncomfortable in other ways, though. Their classes don't implement the Map or List interfaces, and the JsonNode interface isn't modifiable.
Is there a better way?
Just to make sure you are aware of it: Jackson can bind JSON to/from Map
s just fine:
Map<String,Object> map = new ObjectMapper().readValue(jsonSource, Map.class);
as well as full POJOs, like others commented:
POJO pojo = new ObjectMapper().readValue(jsonSource, POJO.class);
so that while you can certainly use JsonNode
(aka Tree Model), there are alternative approaches that are often more convenient.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.