简体   繁体   English

以类型安全的方式在Java中表示JSON

[英]Representing JSON in Java in a type-safe way

Is there a good way to represent JSON in Java in a convenient, easy-to-use, type-safe way? 有没有一种简便,易用,类型安全的方式来表示Java中JSON的好方法?

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. 他们的类未实现Map或List接口,并且JsonNode接口不可修改。

Is there a better way? 有没有更好的办法?

Just to make sure you are aware of it: Jackson can bind JSON to/from Map s just fine: 只是为了确保您了解它:Jackson可以将JSON绑定到Map或从Map绑定JSON:

Map<String,Object> map = new ObjectMapper().readValue(jsonSource, Map.class);

as well as full POJOs, like others commented: 以及完整的POJO,就像其他评论一样:

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. 因此,尽管您当然可以使用JsonNode (又称为树模型),但还有其他方法通常更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM