Class JsonNode
- All Implemented Interfaces:
TreeNode
,JsonSerializable
,Iterable<JsonNode>
- Direct Known Subclasses:
BaseJsonNode
As a general design rule, most accessors ("getters") are included
in this base class, to allow for traversing structure without
type casts. Most mutators, however, need to be accessed through
specific sub-classes (such as ObjectNode
and ArrayNode
).
This seems sensible because proper type
information is generally available when building or modifying
trees, but less often when reading a tree (newly built from
parsed JSON content).
Actual concrete sub-classes can be found from package
com.fasterxml.jackson.databind.node
.
Note that it is possible to "read" from nodes, using
method TreeNode.traverse(ObjectCodec)
, which will result in
a JsonParser
being constructed. This can be used for (relatively)
efficient conversations between different representations; and it is what
core databind uses for methods like ObjectMapper.treeToValue(TreeNode, Class)
and ObjectMapper.treeAsTokens(TreeNode)
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enum
Configuration setting used withwithObject(JsonPointer)
method overrides, to indicate which overwrites are acceptable if the path pointer indicates has incompatible nodes (for example, instead of Object node a Null node is encountered).Nested classes/interfaces inherited from interface com.fasterxml.jackson.databind.JsonSerializable
JsonSerializable.Base
-
Method Summary
Modifier and TypeMethodDescriptionboolean
Method that will try to convert value of this node to a Java boolean.boolean
asBoolean
(boolean defaultValue) Method that will try to convert value of this node to a Java boolean.double
asDouble()
Method that will try to convert value of this node to a Java double.double
asDouble
(double defaultValue) Method that will try to convert value of this node to a Java double.int
asInt()
Method that will try to convert value of this node to a Java int.int
asInt
(int defaultValue) Method that will try to convert value of this node to a Java int.long
asLong()
Method that will try to convert value of this node to a Java long.long
asLong
(long defaultValue) Method that will try to convert value of this node to a Java long.abstract String
asText()
Method that will return a valid String representation of the container value, if the node is a value node (methodisValueNode()
returns true), otherwise empty String.Returns the text value of this node or the provideddefaultValue
if this node does not have a text value.final JsonNode
at
(JsonPointer ptr) Method for locating node specified by given JSON pointer instances.final JsonNode
Convenience method that is functionally equivalent to:Returns integer value for this node (asBigInteger
), if and only if this node is numeric (isNumber()
returns true).byte[]
Method to use for accessing binary content of binary nodes (nodes for whichisBinary()
returns true); or for Text Nodes (ones for whichtextValue()
returns non-null value), to read decoded base64 data.boolean
Method to use for accessing JSON boolean values (value literals 'true' and 'false').boolean
Method that can be used to check whether contained value is numeric (returns true forisNumber()
) and can be losslessly converted to integral number (specifically,BigInteger
but potentially others, seecanConvertToInt()
andcanConvertToInt()
).boolean
Method that can be used to check whether this node is a numeric node (isNumber()
would return true) AND its value fits within Java's 32-bit signed integer type,int
.boolean
Method that can be used to check whether this node is a numeric node (isNumber()
would return true) AND its value fits within Java's 64-bit signed integer type,long
.Returns floating point value for this node (asBigDecimal
), if and only if this node is numeric (isNumber()
returns true).abstract <T extends JsonNode>
TdeepCopy()
Method that can be called to get a node that is guaranteed not to allow changing of this node through mutators on this node or any of its children.double
Returns 64-bit floating point (double) value for this node, if and only if this node is numeric (isNumber()
returns true).elements()
Method for accessing all value nodes of this Node, iff this node is a JSON Array or Object node.abstract boolean
Equality for node objects is defined as full (deep) value equality.boolean
equals
(Comparator<JsonNode> comparator, JsonNode other) Entry method for invoking customizable comparison, using passed-inComparator
object.Method for accessing names of all fields for this node, iff this node is an Object node.fields()
abstract JsonNode
findParent
(String fieldName) Method for finding a JSON Object that contains specified field, within this node or its descendants.findParents
(String fieldName) Method for finding a JSON Object that contains specified field, within this node or its descendants.findParents
(String fieldName, List<JsonNode> foundSoFar) abstract JsonNode
Method similar tofindValue(java.lang.String)
, but that will return a "missing node" instead of null if no field is found.abstract JsonNode
Method for finding the first JSON Object field with specified name in this node or its child nodes, and returning value it has.findValues
(String fieldName) Method for finding JSON Object fields with specified name -- both immediate child values and descendants -- and returning found ones as aList
.findValues
(String fieldName, List<JsonNode> foundSoFar) findValuesAsText
(String fieldName) Similar tofindValues(java.lang.String)
, but will additionally convert values into Strings, callingasText()
.findValuesAsText
(String fieldName, List<String> foundSoFar) float
Returns 32-bit floating value for this node, if and only if this node is numeric (isNumber()
returns true).abstract JsonNode
get
(int index) Method for accessing value of the specified element of an array node.Method for accessing value of the specified field of an object node.abstract JsonNodeType
Return the type of this nodeboolean
has
(int index) Method that allows checking whether this node is JSON Array node and contains a value for specified index If this is the case (including case of specified indexing having null as value), returns true; otherwise returns false.boolean
Method that allows checking whether this node is JSON Object node and contains value for specified property.boolean
hasNonNull
(int index) Method that is similar tohas(int)
, but that will returnfalse
for explicitly added nulls.boolean
hasNonNull
(String fieldName) Method that is similar tohas(String)
, but that will returnfalse
for explicitly added nulls.int
intValue()
Returns integer value for this node, if and only if this node is numeric (isNumber()
returns true).boolean
isArray()
Method that returns true if this node is an Array node, false otherwise.boolean
boolean
final boolean
isBinary()
Method that can be used to check if this node represents binary data (Base64 encoded).final boolean
Method that can be used to check if this node was created from JSON boolean value (literals "true" and "false").final boolean
Method that returns true for container nodes: Arrays and Objects.boolean
isDouble()
boolean
isEmpty()
Convenience method that is functionally same as:boolean
isFloat()
boolean
boolean
isInt()
Method that can be used to check whether contained value is a number represented as Javaint
.boolean
boolean
isLong()
Method that can be used to check whether contained value is a number represented as Javalong
.boolean
Method that returns true for "virtual" nodes which represent missing entries constructed by path accessor methods when there is no actual node matching given criteria.final boolean
isNull()
Method that can be used to check if this node was created from JSON literal null value.final boolean
isNumber()
boolean
isObject()
Method that returns true if this node is an Object node, false otherwise.final boolean
isPojo()
Method that can be used to check if the node is a wrapper for a POJO ("Plain Old Java Object" aka "bean".boolean
isShort()
Method that can be used to check whether contained value is a number represented as Javashort
.final boolean
Method that checks whether this node represents basic JSON String value.final boolean
Method that returns true for all value nodes: ones that are not containers, and that do not represent "missing" nodes in the path.iterator()
Same as callingelements()
; implemented so that convenience "for-each" loop can be used for looping over elements of JSON Array constructs.long
Returns 64-bit long value for this node, if and only if this node is numeric (isNumber()
returns true).Returns numeric value for this node, if and only if this node is numeric (isNumber()
returns true); otherwise returns nullabstract JsonNode
path
(int index) This method is similar toget(int)
, except that instead of returning null if no such element exists (due to index being out of range, or this node not being an array), a "missing node" (node that returns true forisMissingNode()
) will be returned.abstract JsonNode
This method is similar toget(String)
, except that instead of returning null if no such value exists (due to this node not being an object, or object not having value for the specified field), a "missing node" (node that returns true forisMissingNode()
) will be returned.Accessor that will return properties ofObjectNode
similar to howMap.entrySet()
works; for other node types will return emptySet
.<T extends JsonNode>
Trequire()
Method that may be called to verify thatthis
node is NOT so-called "missing node": that is, one for whichisMissingNode()
returnstrue
.required
(int index) Method is functionally equivalent topath(index).required()
and can be used to check that this node is anArrayNode
(that is, represents JSON Array value) and has value for specifiedindex
(but note that value may be explicit JSON null value).Method is functionally equivalent topath(fieldName).required()
and can be used to check that this node is anObjectNode
(that is, represents JSON Object value) and has value for specified property with keyfieldName
(but note that value may be explicit JSON null value).final JsonNode
requiredAt
(JsonPointer path) Method is functionally equivalent toat(path).required()
and can be used to check that there is an actual value node at specifiedJsonPointer
starting fromthis
node (but note that value may be explicit JSON null value).requiredAt
(String pathExpr) Method is functionally equivalent toat(pathExpr).required()
and can be used to check that there is an actual value node at specifiedJsonPointer
starting fromthis
node (but note that value may be explicit JSON null value).<T extends JsonNode>
TMethod that may be called to verify thatthis
node is neither so-called "missing node" (that is, one for whichisMissingNode()
returnstrue
) nor "null node" (one for whichisNull()
returnstrue
).short
Returns 16-bit short value for this node, if and only if this node is numeric (isNumber()
returns true).int
size()
Method that returns number of child nodes this node contains: for Array nodes, number of child elements, for Object nodes, number of fields, and for all other nodes 0.Method to use for accessing String values.Alternative totoString()
that will serialize this node using Jackson default pretty-printer.abstract String
toString()
Method that will produce (as of Jackson 2.10) valid JSON using default settings of databind, as String.<T extends JsonNode>
TDeprecated.final ArrayNode
withArray
(JsonPointer ptr) Same aswithArray(JsonPointer, OverwriteMode, boolean)
but with defaults ofOvewriteMode#NULLS
(overwrite mode) andtrue
forpreferIndex
.withArray
(JsonPointer ptr, JsonNode.OverwriteMode overwriteMode, boolean preferIndex) Method that can be called on Object or Array nodes, to access a Array-valued node pointed to by givenJsonPointer
, if such a node exists: or if not, an attempt is made to create one and return it.<T extends JsonNode>
TMethod that works in one of possible ways, depending on whetherexprOrProperty
is a validJsonPointer
expression or not (valid expression is either empty String""
or starts with leading slash/
character).withArray
(String expr, JsonNode.OverwriteMode overwriteMode, boolean preferIndex) Short-cut equivalent to:withArrayProperty
(String propName) Method similar towithArray(JsonPointer, OverwriteMode, boolean)
-- basically short-cut to:final ObjectNode
withObject
(JsonPointer ptr) Same aswithObject(JsonPointer, OverwriteMode, boolean)
but with defaults ofOvewriteMode#NULLS
(overwrite mode) andtrue
forpreferIndex
(that is, will try to considerJsonPointer
segments index if at all possible and only secondarily as property namewithObject
(JsonPointer ptr, JsonNode.OverwriteMode overwriteMode, boolean preferIndex) Method that can be called on Object or Array nodes, to access a Object-valued node pointed to by givenJsonPointer
, if such a node exists: or if not, an attempt is made to create one and return it.withObject
(String exprOrProperty) Method that works in one of possible ways, depending on whetherexprOrProperty
is a validJsonPointer
expression or not (valid expression is either empty String""
or starts with leading slash/
character).final ObjectNode
withObject
(String expr, JsonNode.OverwriteMode overwriteMode, boolean preferIndex) Short-cut equivalent to:withObjectProperty
(String propName) Method similar towithObject(JsonPointer, OverwriteMode, boolean)
-- basically short-cut to:Methods inherited from class com.fasterxml.jackson.databind.JsonSerializable.Base
isEmpty
Methods inherited from class java.lang.Object
getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.lang.Iterable
forEach, spliterator
Methods inherited from interface com.fasterxml.jackson.databind.JsonSerializable
serialize, serializeWithType
Methods inherited from interface com.fasterxml.jackson.core.TreeNode
asToken, numberType, traverse, traverse
-
Method Details
-
deepCopy
Method that can be called to get a node that is guaranteed not to allow changing of this node through mutators on this node or any of its children. This means it can either make a copy of this node (and all mutable children and grand children nodes), or node itself if it is immutable.Note: return type is guaranteed to have same type as the node method is called on; which is why method is declared with local generic type.
- Returns:
- Node that is either a copy of this node (and all non-leaf children); or, for immutable leaf nodes, node itself.
- Since:
- 2.0
-
size
public int size()Description copied from interface:TreeNode
Method that returns number of child nodes this node contains: for Array nodes, number of child elements, for Object nodes, number of fields, and for all other nodes 0. -
isEmpty
public boolean isEmpty()Convenience method that is functionally same as:size() == 0
for all node types.- Since:
- 2.10
-
isValueNode
public final boolean isValueNode()Description copied from interface:TreeNode
Method that returns true for all value nodes: ones that are not containers, and that do not represent "missing" nodes in the path. Such value nodes represent String, Number, Boolean and null values from JSON.Note: one and only one of methods
TreeNode.isValueNode()
,TreeNode.isContainerNode()
andTreeNode.isMissingNode()
ever returns true for any given node.- Specified by:
isValueNode
in interfaceTreeNode
- Returns:
- True if this node is considered a value node; something that
represents either a scalar value or explicit
null
-
isContainerNode
public final boolean isContainerNode()Description copied from interface:TreeNode
Method that returns true for container nodes: Arrays and Objects.Note: one and only one of methods
TreeNode.isValueNode()
,TreeNode.isContainerNode()
andTreeNode.isMissingNode()
ever returns true for any given node.- Specified by:
isContainerNode
in interfaceTreeNode
- Returns:
True
for Array and Object nodes,false
otherwise
-
isMissingNode
public boolean isMissingNode()Description copied from interface:TreeNode
Method that returns true for "virtual" nodes which represent missing entries constructed by path accessor methods when there is no actual node matching given criteria.Note: one and only one of methods
TreeNode.isValueNode()
,TreeNode.isContainerNode()
andTreeNode.isMissingNode()
ever returns true for any given node.- Specified by:
isMissingNode
in interfaceTreeNode
- Returns:
True
if this node represents a "missing" node
-
isArray
public boolean isArray()Description copied from interface:TreeNode
Method that returns true if this node is an Array node, false otherwise. Note that if true is returned,TreeNode.isContainerNode()
must also return true. -
isObject
public boolean isObject()Description copied from interface:TreeNode
Method that returns true if this node is an Object node, false otherwise. Note that if true is returned,TreeNode.isContainerNode()
must also return true. -
get
Method for accessing value of the specified element of an array node. For other nodes, null is always returned.For array nodes, index specifies exact location within array and allows for efficient iteration over child elements (underlying storage is guaranteed to be efficiently indexable, i.e. has random-access to elements). If index is less than 0, or equal-or-greater than
node.size()
, null is returned; no exception is thrown for any index.NOTE: if the element value has been explicitly set as
null
(which is different from removal!), aNullNode
will be returned, not null. -
get
Method for accessing value of the specified field of an object node. If this node is not an object (or it does not have a value for specified field name), or if there is no field with such name, null is returned.NOTE: if the property value has been explicitly set as
null
(which is different from removal!), aNullNode
will be returned, not null. -
path
This method is similar toget(String)
, except that instead of returning null if no such value exists (due to this node not being an object, or object not having value for the specified field), a "missing node" (node that returns true forisMissingNode()
) will be returned. This allows for convenient and safe chained access via path calls. -
path
This method is similar toget(int)
, except that instead of returning null if no such element exists (due to index being out of range, or this node not being an array), a "missing node" (node that returns true forisMissingNode()
) will be returned. This allows for convenient and safe chained access via path calls. -
fieldNames
Description copied from interface:TreeNode
Method for accessing names of all fields for this node, iff this node is an Object node. Number of field names accessible will beTreeNode.size()
.- Specified by:
fieldNames
in interfaceTreeNode
- Returns:
- An iterator for traversing names of all fields this Object node
has (if Object node); empty
Iterator
otherwise (nevernull
).
-
at
Method for locating node specified by given JSON pointer instances. Method will never return null; if no matching node exists, will return a node for whichisMissingNode()
returns true.- Specified by:
at
in interfaceTreeNode
- Parameters:
ptr
-JsonPointer
expression for descendant node to return- Returns:
- Node that matches given JSON Pointer: if no match exists,
will return a node for which
isMissingNode()
returns true. - Since:
- 2.3
-
at
Convenience method that is functionally equivalent to:return at(JsonPointer.valueOf(jsonPointerExpression));
Note that if the same expression is used often, it is preferable to construct
JsonPointer
instance once and reuse it: this method will not perform any caching of compiled expressions.- Specified by:
at
in interfaceTreeNode
- Parameters:
jsonPtrExpr
- Expression to compile as aJsonPointer
instance- Returns:
- Node that matches given JSON Pointer: if no match exists,
will return a node for which
TreeNode.isMissingNode()
returns true. - Since:
- 2.3
-
getNodeType
Return the type of this node- Returns:
- the node type as a
JsonNodeType
enum value - Since:
- 2.2
-
isPojo
public final boolean isPojo()Method that can be used to check if the node is a wrapper for a POJO ("Plain Old Java Object" aka "bean". Returns true only for instances ofPOJONode
.- Returns:
- True if this node wraps a POJO
-
isNumber
public final boolean isNumber()- Returns:
- True if this node represents a numeric JSON value
-
isIntegralNumber
public boolean isIntegralNumber()- Returns:
- True if this node represents an integral (integer) numeric JSON value
-
isFloatingPointNumber
public boolean isFloatingPointNumber()- Returns:
- True if this node represents a non-integral numeric JSON value
-
isShort
public boolean isShort()Method that can be used to check whether contained value is a number represented as Javashort
. Note, however, that even if this method returns false, it is possible that conversion would be possible from other numeric types -- to check if this is possible, usecanConvertToInt()
instead.- Returns:
- True if the value contained by this node is stored as Java short
-
isInt
public boolean isInt()Method that can be used to check whether contained value is a number represented as Javaint
. Note, however, that even if this method returns false, it is possible that conversion would be possible from other numeric types -- to check if this is possible, usecanConvertToInt()
instead.- Returns:
- True if the value contained by this node is stored as Java int
-
isLong
public boolean isLong()Method that can be used to check whether contained value is a number represented as Javalong
. Note, however, that even if this method returns false, it is possible that conversion would be possible from other numeric types -- to check if this is possible, usecanConvertToLong()
instead.- Returns:
- True if the value contained by this node is stored as Java
long
-
isFloat
public boolean isFloat()- Since:
- 2.2
-
isDouble
public boolean isDouble() -
isBigDecimal
public boolean isBigDecimal() -
isBigInteger
public boolean isBigInteger() -
isTextual
public final boolean isTextual()Method that checks whether this node represents basic JSON String value. -
isBoolean
public final boolean isBoolean()Method that can be used to check if this node was created from JSON boolean value (literals "true" and "false"). -
isNull
public final boolean isNull()Method that can be used to check if this node was created from JSON literal null value. -
isBinary
public final boolean isBinary()Method that can be used to check if this node represents binary data (Base64 encoded). Although this will be externally written as JSON String value,isTextual()
will return false if this method returns true.- Returns:
- True if this node represents base64 encoded binary data
-
canConvertToInt
public boolean canConvertToInt()Method that can be used to check whether this node is a numeric node (isNumber()
would return true) AND its value fits within Java's 32-bit signed integer type,int
. Note that floating-point numbers are convertible if the integral part fits without overflow (as per standard Java coercion rules)NOTE: this method does not consider possible value type conversion from JSON String into Number; so even if this method returns false, it is possible that
asInt()
could still succeed if node is a JSON String representing integral number, or boolean.- Since:
- 2.0
-
canConvertToLong
public boolean canConvertToLong()Method that can be used to check whether this node is a numeric node (isNumber()
would return true) AND its value fits within Java's 64-bit signed integer type,long
. Note that floating-point numbers are convertible if the integral part fits without overflow (as per standard Java coercion rules)NOTE: this method does not consider possible value type conversion from JSON String into Number; so even if this method returns false, it is possible that
asLong()
could still succeed if node is a JSON String representing integral number, or boolean.- Since:
- 2.0
-
canConvertToExactIntegral
public boolean canConvertToExactIntegral()Method that can be used to check whether contained value is numeric (returns true forisNumber()
) and can be losslessly converted to integral number (specifically,BigInteger
but potentially others, seecanConvertToInt()
andcanConvertToInt()
). Latter part allows floating-point numbers (for whichisFloatingPointNumber()
returnstrue
) that do not have fractional part. Note that "not-a-number" values ofdouble
andfloat
will returnfalse
as they can not be converted to matching integral representations.- Returns:
- True if the value is an actual number with no fractional part; false for non-numeric types, NaN representations of floating-point numbers, and floating-point numbers with fractional part.
- Since:
- 2.12
-
textValue
Method to use for accessing String values. Does NOT do any conversions for non-String value nodes; for non-String values (ones for whichisTextual()
returns false) null will be returned. For String values, null is never returned (but empty Strings may be)- Returns:
- Textual value this node contains, iff it is a textual JSON node (comes from JSON String value entry)
-
binaryValue
Method to use for accessing binary content of binary nodes (nodes for whichisBinary()
returns true); or for Text Nodes (ones for whichtextValue()
returns non-null value), to read decoded base64 data. For other types of nodes, returns null.- Returns:
- Binary data this node contains, iff it is a binary node; null otherwise
- Throws:
IOException
-
booleanValue
public boolean booleanValue()Method to use for accessing JSON boolean values (value literals 'true' and 'false'). For other types, always returns false.- Returns:
- Textual value this node contains, iff it is a textual json node (comes from JSON String value entry)
-
numberValue
Returns numeric value for this node, if and only if this node is numeric (isNumber()
returns true); otherwise returns null- Returns:
- Number value this node contains, if any (null for non-number nodes).
-
shortValue
public short shortValue()Returns 16-bit short value for this node, if and only if this node is numeric (isNumber()
returns true). For other types returns 0. For floating-point numbers, value is truncated using default Java coercion, similar to how cast from double to short operates.- Returns:
- Short value this node contains, if any; 0 for non-number nodes.
-
intValue
public int intValue()Returns integer value for this node, if and only if this node is numeric (isNumber()
returns true). For other types returns 0. For floating-point numbers, value is truncated using default Java coercion, similar to how cast from double to int operates.- Returns:
- Integer value this node contains, if any; 0 for non-number nodes.
-
longValue
public long longValue()Returns 64-bit long value for this node, if and only if this node is numeric (isNumber()
returns true). For other types returns 0. For floating-point numbers, value is truncated using default Java coercion, similar to how cast from double to long operates.- Returns:
- Long value this node contains, if any; 0 for non-number nodes.
-
floatValue
public float floatValue()Returns 32-bit floating value for this node, if and only if this node is numeric (isNumber()
returns true). For other types returns 0.0. For integer values, conversion is done using coercion; this means that an overflow is possible for `long` values- Returns:
- 32-bit float value this node contains, if any; 0.0 for non-number nodes.
- Since:
- 2.2
-
doubleValue
public double doubleValue()Returns 64-bit floating point (double) value for this node, if and only if this node is numeric (isNumber()
returns true). For other types returns 0.0. For integer values, conversion is done using coercion; this may result in overflows withBigInteger
values.- Returns:
- 64-bit double value this node contains, if any; 0.0 for non-number nodes.
- Since:
- 2.2
-
decimalValue
Returns floating point value for this node (asBigDecimal
), if and only if this node is numeric (isNumber()
returns true). For other types returnsBigDecimal.ZERO
.- Returns:
BigDecimal
value this node contains, if numeric node;BigDecimal.ZERO
for non-number nodes.
-
bigIntegerValue
Returns integer value for this node (asBigInteger
), if and only if this node is numeric (isNumber()
returns true). For other types returnsBigInteger.ZERO
.NOTE: In Jackson 2.x MAY throw
StreamConstraintsException
if the scale of the underlyingBigDecimal
is too large to convert (NOTE: thrown "sneakily" in Jackson 2.x due to API compatibility restrictions)- Returns:
BigInteger
value this node contains, if numeric node;BigInteger.ZERO
for non-number nodes.
-
asText
Method that will return a valid String representation of the container value, if the node is a value node (methodisValueNode()
returns true), otherwise empty String. -
asText
Returns the text value of this node or the provideddefaultValue
if this node does not have a text value. Useful for nodes that areMissingNode
orNullNode
, ensuring a default value is returned instead of null or missing indicators.NOTE: This was deprecated in 2.17.0, but as discussed through [databind#4471], was un-deprecated in 2.17.1.
- Parameters:
defaultValue
- The default value to return if this node's text value is absent.- Returns:
- The text value of this node, or defaultValue if the text value is absent.
- Since:
- 2.4
-
asInt
public int asInt()Method that will try to convert value of this node to a Java int. Numbers are coerced using default Java rules; booleans convert to 0 (false) and 1 (true), and Strings are parsed using default Java language integer parsing rules.If representation cannot be converted to an int (including structured types like Objects and Arrays), default value of 0 will be returned; no exceptions are thrown.
-
asInt
public int asInt(int defaultValue) Method that will try to convert value of this node to a Java int. Numbers are coerced using default Java rules; booleans convert to 0 (false) and 1 (true), and Strings are parsed using default Java language integer parsing rules.If representation cannot be converted to an int (including structured types like Objects and Arrays), specified defaultValue will be returned; no exceptions are thrown.
-
asLong
public long asLong()Method that will try to convert value of this node to a Java long. Numbers are coerced using default Java rules; booleans convert to 0 (false) and 1 (true), and Strings are parsed using default Java language integer parsing rules.If representation cannot be converted to a long (including structured types like Objects and Arrays), default value of 0 will be returned; no exceptions are thrown.
-
asLong
public long asLong(long defaultValue) Method that will try to convert value of this node to a Java long. Numbers are coerced using default Java rules; booleans convert to 0 (false) and 1 (true), and Strings are parsed using default Java language integer parsing rules.If representation cannot be converted to a long (including structured types like Objects and Arrays), specified defaultValue will be returned; no exceptions are thrown.
-
asDouble
public double asDouble()Method that will try to convert value of this node to a Java double. Numbers are coerced using default Java rules; booleans convert to 0.0 (false) and 1.0 (true), and Strings are parsed using default Java language integer parsing rules.If representation cannot be converted to an int (including structured types like Objects and Arrays), default value of 0.0 will be returned; no exceptions are thrown.
-
asDouble
public double asDouble(double defaultValue) Method that will try to convert value of this node to a Java double. Numbers are coerced using default Java rules; booleans convert to 0.0 (false) and 1.0 (true), and Strings are parsed using default Java language integer parsing rules.If representation cannot be converted to an int (including structured types like Objects and Arrays), specified defaultValue will be returned; no exceptions are thrown.
-
asBoolean
public boolean asBoolean()Method that will try to convert value of this node to a Java boolean. JSON booleans map naturally; integer numbers other than 0 map to true, and 0 maps to false and Strings 'true' and 'false' map to corresponding values.If representation cannot be converted to a boolean value (including structured types like Objects and Arrays), default value of false will be returned; no exceptions are thrown.
-
asBoolean
public boolean asBoolean(boolean defaultValue) Method that will try to convert value of this node to a Java boolean. JSON booleans map naturally; integer numbers other than 0 map to true, and 0 maps to false and Strings 'true' and 'false' map to corresponding values.If representation cannot be converted to a boolean value (including structured types like Objects and Arrays), specified defaultValue will be returned; no exceptions are thrown.
-
require
Method that may be called to verify thatthis
node is NOT so-called "missing node": that is, one for whichisMissingNode()
returnstrue
. If not missing node,this
is returned to allow chaining; otherwiseIllegalArgumentException
is thrown.- Returns:
this
node to allow chaining- Throws:
IllegalArgumentException
- if this node is "missing node"- Since:
- 2.10
-
requireNonNull
Method that may be called to verify thatthis
node is neither so-called "missing node" (that is, one for whichisMissingNode()
returnstrue
) nor "null node" (one for whichisNull()
returnstrue
). If non-null non-missing node,this
is returned to allow chaining; otherwiseIllegalArgumentException
is thrown.- Returns:
this
node to allow chaining- Throws:
IllegalArgumentException
- if this node is either "missing node" or "null node"- Since:
- 2.10
-
required
Method is functionally equivalent topath(fieldName).required()
and can be used to check that this node is anObjectNode
(that is, represents JSON Object value) and has value for specified property with keyfieldName
(but note that value may be explicit JSON null value). If this node is Object Node and has value for specified property, matching value is returned; otherwiseIllegalArgumentException
is thrown.- Parameters:
propertyName
- Name of property to access- Returns:
- Value of the specified property of this Object node
- Throws:
IllegalArgumentException
- if this node is not an Object node or if it does not have value for specified property- Since:
- 2.10
-
required
Method is functionally equivalent topath(index).required()
and can be used to check that this node is anArrayNode
(that is, represents JSON Array value) and has value for specifiedindex
(but note that value may be explicit JSON null value). If this node is Array Node and has value for specified index, value at index is returned; otherwiseIllegalArgumentException
is thrown.- Parameters:
index
- Index of the value of this Array node to access- Returns:
- Value at specified index of this Array node
- Throws:
IllegalArgumentException
- if this node is not an Array node or if it does not have value for specified index- Since:
- 2.10
-
requiredAt
Method is functionally equivalent toat(pathExpr).required()
and can be used to check that there is an actual value node at specifiedJsonPointer
starting fromthis
node (but note that value may be explicit JSON null value). If such value node exists it is returned; otherwiseIllegalArgumentException
is thrown.- Parameters:
pathExpr
-JsonPointer
expression (as String) to use for finding value node- Returns:
- Matching value node for given expression
- Throws:
IllegalArgumentException
- if no value node exists at givenJSON Pointer
path- Since:
- 2.10
-
requiredAt
Method is functionally equivalent toat(path).required()
and can be used to check that there is an actual value node at specifiedJsonPointer
starting fromthis
node (but note that value may be explicit JSON null value). If such value node exists it is returned; otherwiseIllegalArgumentException
is thrown.- Parameters:
path
-JsonPointer
expression to use for finding value node- Returns:
- Matching value node for given expression
- Throws:
IllegalArgumentException
- if no value node exists at givenJSON Pointer
path- Since:
- 2.10
-
has
Method that allows checking whether this node is JSON Object node and contains value for specified property. If this is the case (including properties with explicit null values), returns true; otherwise returns false.This method is equivalent to:
node.get(fieldName) != null
(since return value of get() is node, not value node contains)NOTE: when explicit
null
values are added, this method will returntrue
for such properties.- Parameters:
fieldName
- Name of element to check- Returns:
- True if this node is a JSON Object node, and has a property entry with specified name (with any value, including null value)
-
has
public boolean has(int index) Method that allows checking whether this node is JSON Array node and contains a value for specified index If this is the case (including case of specified indexing having null as value), returns true; otherwise returns false.Note: array element indexes are 0-based.
This method is equivalent to:
node.get(index) != null
NOTE: this method will return
true
for explicitly added null values.- Parameters:
index
- Index to check- Returns:
- True if this node is a JSON Object node, and has a property entry with specified name (with any value, including null value)
-
hasNonNull
Method that is similar tohas(String)
, but that will returnfalse
for explicitly added nulls.This method is functionally equivalent to:
node.get(fieldName) != null && !node.get(fieldName).isNull()
- Since:
- 2.1
-
hasNonNull
public boolean hasNonNull(int index) Method that is similar tohas(int)
, but that will returnfalse
for explicitly added nulls.This method is equivalent to:
node.get(index) != null && !node.get(index).isNull()
- Since:
- 2.1
-
iterator
Same as callingelements()
; implemented so that convenience "for-each" loop can be used for looping over elements of JSON Array constructs. -
elements
Method for accessing all value nodes of this Node, iff this node is a JSON Array or Object node. In case of Object node, field names (keys) are not included, only values. For other types of nodes, returns empty iterator. -
fields
- Returns:
- Iterator that can be used to traverse all key/value pairs for object nodes; empty iterator (no contents) for other types
-
properties
Accessor that will return properties ofObjectNode
similar to howMap.entrySet()
works; for other node types will return emptySet
.- Returns:
- Set of properties, if this node is an
ObjectNode
(isObject()
returnstrue
); emptySet
otherwise. - Since:
- 2.15
-
findValue
Method for finding the first JSON Object field with specified name in this node or its child nodes, and returning value it has. If no matching field is found in this node or its descendants, returns null.Note that traversal is done in document order (that is, order in which nodes are iterated if using
elements()
)- Parameters:
fieldName
- Name of field to look for- Returns:
- Value of first matching node found, if any; null if none
-
findValues
Method for finding JSON Object fields with specified name -- both immediate child values and descendants -- and returning found ones as aList
. Note that sub-tree search ends when matching field is found, so possible children of result nodes are not included. If no matching fields are found in this node or its descendants, returns an empty List.- Parameters:
fieldName
- Name of field to look for
-
findValuesAsText
Similar tofindValues(java.lang.String)
, but will additionally convert values into Strings, callingasText()
. -
findPath
Method similar tofindValue(java.lang.String)
, but that will return a "missing node" instead of null if no field is found. Missing node is a specific kind of node for whichisMissingNode()
returns true; and all value access methods return empty or missing value.- Parameters:
fieldName
- Name of field to look for- Returns:
- Value of first matching node found; or if not found, a "missing node" (non-null instance that has no value)
-
findParent
Method for finding a JSON Object that contains specified field, within this node or its descendants. If no matching field is found in this node or its descendants, returns null.- Parameters:
fieldName
- Name of field to look for- Returns:
- Value of first matching node found, if any; null if none
-
findParents
Method for finding a JSON Object that contains specified field, within this node or its descendants. If no matching field is found in this node or its descendants, returns null.- Parameters:
fieldName
- Name of field to look for- Returns:
- Value of first matching node found, if any; null if none
-
findValues
-
findValuesAsText
-
findParents
-
withObject
Method that works in one of possible ways, depending on whetherexprOrProperty
is a validJsonPointer
expression or not (valid expression is either empty String""
or starts with leading slash/
character). If it is, works as a short-cut to:withObject(JsonPointer.compile(exprOrProperty));
If it is NOT a validJsonPointer
expression, value is taken as a literal Object property name and calls is alias forwithObjectProperty(exprOrProperty);
- Parameters:
exprOrProperty
-JsonPointer
expression to use (if valid as one), or, if not (no leading "/"), property name to match.- Returns:
ObjectNode
found or created- Since:
- 2.14 (but semantics before 2.16 did NOT allow for non-JsonPointer expressions)
-
withObject
public final ObjectNode withObject(String expr, JsonNode.OverwriteMode overwriteMode, boolean preferIndex) Short-cut equivalent to:withObject(JsonPointer.compile(expr), overwriteMode, preferIndex);
- Since:
- 2.14
-
withObject
Same aswithObject(JsonPointer, OverwriteMode, boolean)
but with defaults ofOvewriteMode#NULLS
(overwrite mode) andtrue
forpreferIndex
(that is, will try to considerJsonPointer
segments index if at all possible and only secondarily as property name- Parameters:
ptr
-JsonPointer
that indicates path to use for Object value to return (potentially creating as necessary)- Returns:
ObjectNode
found or created- Since:
- 2.14
-
withObject
public ObjectNode withObject(JsonPointer ptr, JsonNode.OverwriteMode overwriteMode, boolean preferIndex) Method that can be called on Object or Array nodes, to access a Object-valued node pointed to by givenJsonPointer
, if such a node exists: or if not, an attempt is made to create one and return it. For example, on document{ "a" : { "b" : { "c" : 13 } } }
calling method withJsonPointer
of/a/b
would returnObjectNode
{ "c" : 13 }
In cases where path leads to "missing" nodes, a path is created. So, for example, on above document, and
JsonPointer
of/a/x
an emptyObjectNode
would be returned and the document would look like:{ "a" : { "b" : { "c" : 13 }, "x" : { } } }
Finally, if the path is incompatible with the document -- there is an existingJsonNode
through which expression cannot go -- a replacement is attempted if (and only if) conversion is allowed as peroverwriteMode
passed in. For example, with above document and expression of/a/b/c
, conversion is allowed if passingOverwriteMode.SCALARS
orOvewriteMode.ALL
, and resulting document would look like:{ "a" : { "b" : { "c" : { } }, "x" : { } } }
but if different modes (NONE
orNULLS
) is passed, an exception is thrown instead.- Parameters:
ptr
- Pointer that indicates path to use forObjectNode
value to return (potentially creating one as necessary)overwriteMode
- Defines which node types may be converted in case of incompatibleJsonPointer
expression: if conversion not allowed,UnsupportedOperationException
is thrown.preferIndex
- When creating a path (for empty or replacement), and path contains segment that may be an array index (simple integer number like3
), whether to construct anArrayNode
(true
) orObjectNode
(false
). In latter case matching property with quoted number (like"3"
) is used within Object.- Returns:
ObjectNode
found or created- Throws:
UnsupportedOperationException
- if a conversion would be needed for givenJsonPointer
, document, but was not allowed for the type encountered- Since:
- 2.14
-
withObjectProperty
Method similar towithObject(JsonPointer, OverwriteMode, boolean)
-- basically short-cut to:withObject(JsonPointer.compile("/"+propName), OverwriteMode.NULLS, false);
that is, only matches immediate property onObjectNode
and will either use an existingObjectNode
that is value of the property, or create one if no value or value isNullNode
.
Will fail with an exception if:- Node method called on is NOT
ObjectNode
- Property has an existing value that is NOT
NullNode
(explicitnull
)
- Parameters:
propName
- Name of property that has or will haveObjectNode
as value- Returns:
ObjectNode
value of given property (existing or created)- Since:
- 2.16
- Node method called on is NOT
-
with
Deprecated.Since 2.14 usewithObject(String)
insteadMethod that works in one of possible ways, depending on whetherexprOrProperty
is a validJsonPointer
expression or not (valid expression is either empty String""
or starts with leading slash/
character). If it is, works as a short-cut to:withObject(JsonPointer.compile(exprOrProperty));
If it is NOT a validJsonPointer
expression, value is taken as a literal Object property name and traversed like a single-segmentJsonPointer
.NOTE: before Jackson 2.14 behavior was always that of non-expression usage; that is,
exprOrProperty
was always considered as a simple property name. -
withArray
Method that works in one of possible ways, depending on whetherexprOrProperty
is a validJsonPointer
expression or not (valid expression is either empty String""
or starts with leading slash/
character). If it is, works as a short-cut to:withObject(JsonPointer.compile(exprOrProperty));
If it is NOT a validJsonPointer
expression, value is taken as a literal Object property name and traversed like a single-segmentJsonPointer
.NOTE: before Jackson 2.14 behavior was always that of non-expression usage; that is,
exprOrProperty
was always considered as a simple property name.- Parameters:
exprOrProperty
- EitherJsonPointer
expression for full access (if valid pointer expression), or the name of property for theArrayNode
.- Returns:
ArrayNode
found or created
-
withArray
Short-cut equivalent to:withArray(JsonPointer.compile(expr), overwriteMode, preferIndex);
- Since:
- 2.14
-
withArray
Same aswithArray(JsonPointer, OverwriteMode, boolean)
but with defaults ofOvewriteMode#NULLS
(overwrite mode) andtrue
forpreferIndex
. -
withArray
public ArrayNode withArray(JsonPointer ptr, JsonNode.OverwriteMode overwriteMode, boolean preferIndex) Method that can be called on Object or Array nodes, to access a Array-valued node pointed to by givenJsonPointer
, if such a node exists: or if not, an attempt is made to create one and return it. For example, on document{ "a" : { "b" : [ 1, 2 ] } }
calling method withJsonPointer
of/a/b
would returnArray
[ 1, 2 ]
In cases where path leads to "missing" nodes, a path is created. So, for example, on above document, and
JsonPointer
of/a/x
an emptyArrayNode
would be returned and the document would look like:{ "a" : { "b" : [ 1, 2 ], "x" : [ ] } }
Finally, if the path is incompatible with the document -- there is an existingJsonNode
through which expression cannot go -- a replacement is attempted if (and only if) conversion is allowed as peroverwriteMode
passed in. For example, with above document and expression of/a/b/0
, conversion is allowed if passingOverwriteMode.SCALARS
orOvewriteMode.ALL
, and resulting document would look like:{ "a" : { "b" : [ [ ], 2 ], "x" : [ ] } }
but if different modes (NONE
orNULLS
) is passed, an exception is thrown instead.- Parameters:
ptr
- Pointer that indicates path to use forArrayNode
value to return (potentially creating it as necessary)overwriteMode
- Defines which node types may be converted in case of incompatibleJsonPointer
expression: if conversion not allowed, an exception is thrown.preferIndex
- When creating a path (for empty or replacement), and path contains segment that may be an array index (simple integer number like3
), whether to construct anArrayNode
(true
) orObjectNode
(false
). In latter case matching property with quoted number (like"3"
) is used within Object.- Returns:
ArrayNode
found or created- Throws:
UnsupportedOperationException
- if a conversion would be needed for givenJsonPointer
, document, but was not allowed for the type encountered- Since:
- 2.14
-
withArrayProperty
Method similar towithArray(JsonPointer, OverwriteMode, boolean)
-- basically short-cut to:withArray(JsonPointer.compile("/"+propName), OverwriteMode.NULLS, false);
that is, only matches immediate property onObjectNode
and will either use an existingArrayNode
that is value of the property, or create one if no value or value isNullNode
.
Will fail with an exception if:- Node method called on is NOT
ObjectNode
- Property has an existing value that is NOT
NullNode
(explicitnull
)
- Node method called on is NOT
-
equals
Entry method for invoking customizable comparison, using passed-inComparator
object. Nodes will handle traversal of structured types (arrays, objects), but defer to comparator for scalar value comparisons. If a "natural"Comparator
is passed -- one that simply callsequals()
on one of arguments, passing the other -- implementation is the same as directly callingequals()
on node.Default implementation simply delegates to passed in
comparator
, withthis
as the first argument, andother
as the second argument.- Parameters:
comparator
- Object called to compare two scalarJsonNode
instances, and return either 0 (are equals) or non-zero (not equal)- Since:
- 2.6
-
toString
Method that will produce (as of Jackson 2.10) valid JSON using default settings of databind, as String. If you want other kinds of JSON output (or output formatted using one of other Jackson-supported data formats) make sure to useObjectMapper
orObjectWriter
to serialize an instance, for example:String json = objectMapper.writeValueAsString(rootNode);
Note: method defined as abstract to ensure all implementation classes explicitly implement method, instead of relying on
Object.toString()
definition. -
toPrettyString
Alternative totoString()
that will serialize this node using Jackson default pretty-printer.- Since:
- 2.10
-
equals
Equality for node objects is defined as full (deep) value equality. This means that it is possible to compare complete JSON trees for equality by comparing equality of root nodes.Note: marked as abstract to ensure all implementation classes define it properly and not rely on definition from
Object
.
-
withObject(String)
instead