Jackson的ObjectMapper是否可以从
JSON树中的特定节点(和“down”)取消编组?
用例是可扩展的文档格式.我想走树,然后将当前路径发布到可扩展的插件集,以查看用户是否正在使用,以及知道该文档该部分应该怎么做的插件.
我想让插件作者不必处理JsonNode或流API的低级细节;相反,只是传递一些上下文和一个特定的JsonNode,然后可以使用可爱和方便的ObjectMapper来解组他们的类的实例,考虑以树的根传递的节点.
解决方法
考虑以下JSON:
{ "firstName": "John","lastName": "Doe","address": { "street": "21 2nd Street","city": "New York","postalCode": "10021-3100","coordinates": { "latitude": 40.7250387,"longitude": -73.9932568 } } }
并且考虑您要将坐标节点解析为以下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 Pointer查询坐标节点,并使用ObjectMapper
将其解析为坐标类:
JsonNode coordinatesNode = node.at("/address/coordinates"); Coordinates coordinates = mapper.treeToValue(coordinatesNode,Coordinates.class);
JSON指针是一种遍历JSON的路径语言.有关更多详细信息,请查看RFC 6901.自2.3版本起,它在Jackson中可用.