杰克逊的Json accesing JsonNode属性名
问题描述:
我有这样一个模式:杰克逊的Json accesing JsonNode属性名
{
"type" : "object",
"$schema" : "http://json-schema.org/draft-03/schema#",
"id" : "urn:jsonschema:com:vlashel:dto:UserDto",
"description" : "this is the top description",
"title" : "this is the top title",
"properties" : {
"number" : {
"type" : "integer"
"required" : true
},
"password" : {
"type" : "string"
"required" : true
}
}
我有以下的代码,将这个shcema草案3通过删除“要求”起草4,我想收集节点的属性名称那些在他们身上有“需求”的人。我怎么做?我没有看到这方法..
JsonNode jsonNode = jsonNodeIterator.next();
ObjectNode element;
if (jsonNode instanceof ObjectNode) {
element = (ObjectNode) jsonNode;
element.remove("required");
String propertyName = element.getPropertyName(); //I'm looking for this kind of method.
谢谢!
答
通过使用List<JsonNode> findParents(String fieldName)
,您可以获得具有该属性的所有节点,它可以为您提供此功能。来自文档:
用于查找包含指定字段的JSON对象的方法,该节点或其子代在 之内。如果在此 节点或其后代中未找到匹配的字段,则返回null。
我做了一个快速的例子,但不得不添加几个字符到您发布的JSON blob,因为它缺少一些逗号和括号,并且无法被ObjectMapper读取。这很简单,只要这样的:
JsonNode root = mapper.readTree(SCHEMA);
List<JsonNode> required = root.findParents("required");
for (JsonNode node: required) {
Object prettyOutput = mapper.readValue(node, Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(prettyOutput));
}
输出:
{
"type" : "integer",
"required" : true
}
{
"type" : "string",
"required" : true
}
哪个属性? ObjectNode是一个具有多个属性的对象。你可以用Iterator> getFields()来迭代它们,但我不确定你在找什么。 –
mkobit
2014-09-30 18:03:13
这实际上是我喜欢的)谢谢 – vlashel 2014-10-03 19:06:57