Skip to content

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

Closed

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.

Activity

  1. added a commit that references this issue on Aug 29, 2019
    8f0b80d
  2. cowtowncoder commented on Aug 29, 2019

    @cowtowncoder
    MemberAuthor

    Methods added as suggested: for 2.x (at least), failure indicated by IllegalArgumentException: for 3.x will change to new unchecked Jackson-specific exceptions.

  3. added this to the 2.10.0.pr2 milestone on Aug 29, 2019
  4. added a commit that references this issue on Nov 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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