栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Jackson映射JSON树中特定节点的对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Jackson映射JSON树中特定节点的对象

考虑以下JSON:

{  "firstName": "John",  "lastName": "Doe",  "address": {    "street": "21 2nd Street",    "city": "New York",    "postalCode": "10021-3100",    "coordinates": {      "latitude": 40.7250387,      "longitude": -73.9932568    }  }}

并考虑将

coordinates
节点解析为以下Java类:

public class Coordinates {    private Double latitude;    private Double longitude;    // Default constructor, getters and setters omitted}

要做到这一点,分析整个JSON成

JsonNode
具有
ObjectMapper

String json = "{"firstName":"John","lastName":"Doe","address":{"street":" + ""21 2nd Street","city":"New York","postalCode":"10021-3100"," + ""coordinates":{"latitude":40.7250387,"longitude":-73.9932568}}}";ObjectMapper mapper = new ObjectMapper();JsonNode node = mapper.readTree(json);

然后使用JSON指针查询

coordinates
节点并将
ObjectMapper
其解析为
Coordinates
该类:

JsonNode coordinatesNode = node.at("/address/coordinates");Coordinates coordinates = mapper.treeToValue(coordinatesNode, Coordinates.class);

JSON指针是遍历JSON的路径语言。有关更多详细信息,请检查RFC
6901
。从2.3版开始,它就可以在Jackson中使用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427627.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号