Skip to content

Add "required" methods in JsonNode: required(String | int), requiredAt(JsonPointer) #2237

@cowtowncoder

Description

@cowtowncoder

As per ideas on https://github.com/FasterXML/jackson-future-ideas/wiki/Jackson3-Changes---JsonNode it seems we could add couple of new, useful "validating" accessor methods, similar to how many other Java JSON libraries mandate presence of value when using accessors.

Here's a suggested list:

  • required(locator): similar to get(locator) and path(locator) but will throw exception (instead of returning null or MissingNode) with message indicating locator
    • locator is either property name (for Objects) or int index (for Arrays), same as with other accessors
    • Returns JsonNode at location, guaranteed not to be null or MissingNode
    • Exception to throw needs to be unchecked exception, even for 2.10 (in 3.0 we will likely change all Jackson exceptions to be unchecked) -- partly since we do not have access to context with any of the accessors
  • requiredAt(jsonPointer) (either String or pre-compiled JsonPointer)
    • same as above, but allows convenient single-call verificatiion
  • require(): verify that node is NOT missingNode; if it is, throw same exception as previous accessors would
    • essentially, root.required("foo") would be equivalent to root.path("foo").require() (except for slightly different error message)
    • returns this
  • requireNonNull(): similarly to require(), but also throw exception if "this" is NullNode (returns true for isNull())

So: these could improve JsonNode ergonomics a lot.

There are obviously many more we could consider (for example, whole set of requireInt() or such), but I think incremental improvements are a good way to go here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions