使用 Jackson 从 JSON 树中的特定节点映射对象 [英] Using Jackson to map object from specific node in JSON tree
问题描述
是否可以让 Jackson 的 ObjectMapper
仅从 JSON 树中的特定节点(和向下")解组?
Is it possible to have Jackson's ObjectMapper
unmarshall only from a specific node (and 'down') in a JSON tree?
用例是一种可扩展的文档格式.我想遍历树,然后将当前路径发布到一组可扩展的插件,以查看用户是否正在使用以及知道如何处理该部分文档的插件.
The use case is an extensible document format. I want to walk the tree, and then publish the current path to an extensible set of plugins, to see if the user is using and plugins that know what to do with that part of the document.
我希望插件作者不必处理 JsonNode
或流 API 的底层细节;相反,只需传递一些上下文和特定的 JsonNode
,然后就可以使用可爱且方便的 ObjectMapper
来解组其类的实例,考虑传递的节点为树的根.
I'd like for plugin authors to not have to deal with the low-level details of JsonNode
or the streaming API; instead, just be passed some context and a specific JsonNode
, and then be able to use the lovely and convenient ObjectMapper
to unmarshall an instance of their class, considering the node passed as the root of the tree.
推荐答案
考虑以下 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 类:
And consider you want to parse the coordinates
node into the following Java class:
public class Coordinates {
private Double latitude;
private Double longitude;
// Default constructor, getters and setters omitted
}
为此,将整个 JSON 解析为 JsonNode
和 ObjectMapper
:
To do it, parse the whole JSON into a JsonNode
with 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 Pointer查询坐标
节点并使用 ObjectMapper
将其解析为 Coordinates
类:
Then use JSON Pointer to query the coordinates
node and use ObjectMapper
to parse it into the Coordinates
class:
JsonNode coordinatesNode = node.at("/address/coordinates");
Coordinates coordinates = mapper.treeToValue(coordinatesNode, Coordinates.class);
JSON Pointer 是一种遍历 JSON 的路径语言.有关更多详细信息,请查看 RFC 6901.从 2.3 版开始,它在 Jackson 中可用.
JSON Pointer is a path language to traverse JSON. For more details, check the RFC 6901. It is available in Jackson since the version 2.3.
这篇关于使用 Jackson 从 JSON 树中的特定节点映射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!