使用Jackson从JSON树中的特定节点映射对象 [英] Using Jackson to map object from specific node in JSON tree
问题描述
是否可以让杰克逊的 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
}
}
}
并且考虑要将坐标
节点解析为以下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指针查询坐标
节点并使用 ObjectMapper
将其解析为坐标
类:
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指针是一种遍历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屋!