Jackson Json whose name belongs to JsonNode

I have a scheme like this:

{
  "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

    }
}

      

I have the following code that converts this shcema 3 project to draft 4 by removing the "required", I want to collect the property names of the nodes that have "requred" in them. How should I do it? I don't see any methods for this.

             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.

      

Thank!

+3


source to share


1 answer


You can get all the nodes that have this property using List<JsonNode> findParents(String fieldName)

what does it for you. From the docs:

The search method for the JSON object that contains the specified field is within node or its descendants If a matching node or its descendants are found in this field, returns null.

I made a quick example, but I had to add some characters to the JSON sign you posted as it is missing some commas and parentheses and cannot be read by the ObjectMapper. It is so simple:



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));
}

      

Output:

{
  "type" : "integer",
  "required" : true
}
{
  "type" : "string",
  "required" : true
}

      

+2


source







All Articles