or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdannotations.mdconfiguration.mddeserialization.mdindex.mdjson-tree-model.mdmodules.mdobject-mapping.mdserialization.mdtype-system.md

json-tree-model.mddocs/

0

# JSON Tree Model

1

2

Jackson's JSON Tree Model provides an in-memory tree representation of JSON content, similar to XML DOM. The model is centered around the JsonNode hierarchy, which allows navigation and manipulation of JSON structures without binding to specific Java classes.

3

4

## JsonNode Hierarchy

5

6

The JsonNode tree model consists of a hierarchy of node types representing different JSON value types.

7

8

```java { .api }

9

public abstract class JsonNode implements TreeNode, Iterable<JsonNode> {

10

// Navigation methods

11

public abstract JsonNode get(int index);

12

public JsonNode get(String fieldName);

13

public abstract JsonNode path(String fieldName);

14

public abstract JsonNode path(int index);

15

public JsonNode at(String jsonPtrExpr);

16

public JsonNode at(JsonPointer ptr);

17

public JsonNode findValue(String fieldName);

18

public List<JsonNode> findValues(String fieldName, List<JsonNode> foundSoFar);

19

public List<String> findValuesAsText(String fieldName, List<String> foundSoFar);

20

public JsonNode findPath(String fieldName);

21

public JsonNode findParent(String fieldName);

22

23

// Type checking methods

24

public abstract boolean isArray();

25

public abstract boolean isObject();

26

public final boolean isValueNode();

27

public final boolean isContainerNode();

28

public final boolean isMissingNode();

29

public boolean isNull();

30

public boolean isTextual();

31

public boolean isNumber();

32

public boolean isBoolean();

33

public boolean isBinary();

34

public boolean isPojo();

35

public boolean isFloatingPointNumber();

36

public boolean isIntegralNumber();

37

public boolean isShort();

38

public boolean isInt();

39

public boolean isLong();

40

public boolean isFloat();

41

public boolean isDouble();

42

public boolean isBigDecimal();

43

public boolean isBigInteger();

44

45

// Node type enumeration

46

public abstract JsonNodeType getNodeType();

47

48

// Value extraction methods

49

public String asText();

50

public String asText(String defaultValue);

51

public int asInt();

52

public int asInt(int defaultValue);

53

public long asLong();

54

public long asLong(long defaultValue);

55

public double asDouble();

56

public double asDouble(double defaultValue);

57

public boolean asBoolean();

58

public boolean asBoolean(boolean defaultValue);

59

public BigInteger asBigInteger();

60

public BigInteger asBigInteger(BigInteger defaultValue);

61

62

// Raw value access (type-specific)

63

public String textValue();

64

public byte[] binaryValue() throws IOException;

65

public boolean booleanValue();

66

public Number numberValue();

67

public short shortValue();

68

public int intValue();

69

public long longValue();

70

public float floatValue();

71

public double doubleValue();

72

public BigDecimal decimalValue();

73

public BigInteger bigIntegerValue();

74

75

// Container methods

76

public abstract int size();

77

public abstract boolean isEmpty();

78

public boolean has(String fieldName);

79

public boolean has(int index);

80

public boolean hasNonNull(String fieldName);

81

public boolean hasNonNull(int index);

82

public Iterator<String> fieldNames();

83

public Iterator<Map.Entry<String, JsonNode>> fields();

84

public Iterator<JsonNode> elements();

85

86

// Iteration support

87

public Iterator<JsonNode> iterator();

88

89

// Serialization

90

public abstract void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

91

public abstract void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException;

92

93

// JSON Pointer support

94

public JsonNode at(JsonPointer ptr);

95

public JsonNode at(String jsonPtrExpr);

96

97

// Tree traversal

98

public abstract JsonNode deepCopy();

99

100

// Comparison

101

public abstract boolean equals(Object o);

102

public final boolean equals(Comparator<JsonNode> comparator, JsonNode other);

103

104

// String representation

105

public abstract String toString();

106

public String toPrettyString();

107

108

// Required fields checking (for validation)

109

public JsonNode required(String fieldName) throws IllegalArgumentException;

110

public JsonNode required(int index) throws IllegalArgumentException;

111

public JsonNode requiredAt(String pathExpr) throws IllegalArgumentException;

112

public JsonNode requiredAt(JsonPointer path) throws IllegalArgumentException;

113

114

// With methods (for creating modified copies)

115

public JsonNode with(String propertyName);

116

public JsonNode withArray(String propertyName);

117

}

118

119

// Node type enumeration

120

public enum JsonNodeType {

121

ARRAY, BINARY, BOOLEAN, MISSING, NULL, NUMBER, OBJECT, POJO, STRING

122

}

123

```

124

125

## Container Nodes

126

127

Container nodes represent JSON objects and arrays that can contain other nodes.

128

129

### ObjectNode

130

131

ObjectNode represents JSON objects with key-value pairs.

132

133

```java { .api }

134

public class ObjectNode extends ContainerNode<ObjectNode> implements Serializable {

135

// Construction

136

public ObjectNode(JsonNodeFactory nc);

137

public ObjectNode(JsonNodeFactory nc, Map<String, JsonNode> kids);

138

139

// Field manipulation

140

public JsonNode set(String fieldName, JsonNode value);

141

public JsonNode setAll(Map<String,? extends JsonNode> properties);

142

public JsonNode setAll(ObjectNode other);

143

public JsonNode replace(String fieldName, JsonNode value);

144

public JsonNode put(String fieldName, JsonNode value);

145

public JsonNode putNull(String fieldName);

146

public JsonNode put(String fieldName, short value);

147

public JsonNode put(String fieldName, int value);

148

public JsonNode put(String fieldName, long value);

149

public JsonNode put(String fieldName, float value);

150

public JsonNode put(String fieldName, double value);

151

public JsonNode put(String fieldName, BigDecimal value);

152

public JsonNode put(String fieldName, BigInteger value);

153

public JsonNode put(String fieldName, String value);

154

public JsonNode put(String fieldName, boolean value);

155

public JsonNode put(String fieldName, byte[] value);

156

public JsonNode putPOJO(String fieldName, Object pojo);

157

public JsonNode putRawValue(String fieldName, RawValue raw);

158

159

// Array field creation

160

public ArrayNode putArray(String fieldName);

161

public ObjectNode putObject(String fieldName);

162

163

// Field removal

164

public JsonNode remove(String fieldName);

165

public JsonNode remove(Collection<String> fieldNames);

166

public ObjectNode removeAll();

167

public ObjectNode retain(Collection<String> fieldNames);

168

public ObjectNode retain(String... fieldNames);

169

170

// Without methods (creates copy without specified fields)

171

public ObjectNode without(String fieldName);

172

public ObjectNode without(Collection<String> fieldNames);

173

174

// Field access

175

public JsonNode findValue(String fieldName);

176

public ObjectNode findParent(String fieldName);

177

public List<JsonNode> findValues(String fieldName, List<JsonNode> foundSoFar);

178

public List<String> findValuesAsText(String fieldName, List<String> foundSoFar);

179

public ObjectNode findParents(String fieldName, List<JsonNode> foundSoFar);

180

181

// Iteration

182

public Iterator<Map.Entry<String, JsonNode>> fields();

183

public Iterator<String> fieldNames();

184

public Iterator<JsonNode> elements();

185

186

// Properties access

187

public Collection<String> properties();

188

public Set<String> keySet();

189

190

// Container methods

191

public int size();

192

public boolean isEmpty();

193

public boolean has(String fieldName);

194

public boolean has(int index);

195

public boolean hasNonNull(String fieldName);

196

public boolean hasNonNull(int index);

197

198

// Navigation

199

public JsonNode get(int index);

200

public JsonNode get(String fieldName);

201

public JsonNode path(String fieldName);

202

public JsonNode path(int index);

203

204

// Type information

205

public JsonNodeType getNodeType();

206

public boolean isObject();

207

208

// Copying

209

public ObjectNode deepCopy();

210

211

// Conversion

212

public String toString();

213

214

// Serialization

215

public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

216

public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException;

217

}

218

```

219

220

### ArrayNode

221

222

ArrayNode represents JSON arrays containing ordered sequences of nodes.

223

224

```java { .api }

225

public class ArrayNode extends ContainerNode<ArrayNode> implements Serializable {

226

// Construction

227

public ArrayNode(JsonNodeFactory nf);

228

public ArrayNode(JsonNodeFactory nf, int capacity);

229

public ArrayNode(JsonNodeFactory nf, List<JsonNode> children);

230

231

// Element addition

232

public ArrayNode add(JsonNode value);

233

public ArrayNode add(short value);

234

public ArrayNode add(int value);

235

public ArrayNode add(long value);

236

public ArrayNode add(float value);

237

public ArrayNode add(double value);

238

public ArrayNode add(BigDecimal value);

239

public ArrayNode add(BigInteger value);

240

public ArrayNode add(String value);

241

public ArrayNode add(boolean value);

242

public ArrayNode add(byte[] value);

243

public ArrayNode addNull();

244

public ArrayNode addPOJO(Object pojo);

245

public ArrayNode addRawValue(RawValue raw);

246

public ArrayNode addAll(ArrayNode other);

247

public ArrayNode addAll(Collection<? extends JsonNode> nodes);

248

249

// Container addition

250

public ArrayNode addArray();

251

public ObjectNode addObject();

252

253

// Element insertion

254

public ArrayNode insert(int index, JsonNode value);

255

public ArrayNode insert(int index, short value);

256

public ArrayNode insert(int index, int value);

257

public ArrayNode insert(int index, long value);

258

public ArrayNode insert(int index, float value);

259

public ArrayNode insert(int index, double value);

260

public ArrayNode insert(int index, BigDecimal value);

261

public ArrayNode insert(int index, BigInteger value);

262

public ArrayNode insert(int index, String value);

263

public ArrayNode insert(int index, boolean value);

264

public ArrayNode insert(int index, byte[] value);

265

public ArrayNode insertNull(int index);

266

public ArrayNode insertPOJO(int index, Object pojo);

267

268

// Container insertion

269

public ArrayNode insertArray(int index);

270

public ObjectNode insertObject(int index);

271

272

// Element modification

273

public JsonNode set(int index, JsonNode value);

274

public ArrayNode set(int index, short value);

275

public ArrayNode set(int index, int value);

276

public ArrayNode set(int index, long value);

277

public ArrayNode set(int index, float value);

278

public ArrayNode set(int index, double value);

279

public ArrayNode set(int index, BigDecimal value);

280

public ArrayNode set(int index, BigInteger value);

281

public ArrayNode set(int index, String value);

282

public ArrayNode set(int index, boolean value);

283

public ArrayNode set(int index, byte[] value);

284

public ArrayNode setNull(int index);

285

public ArrayNode setPOJO(int index, Object pojo);

286

287

// Element removal

288

public JsonNode remove(int index);

289

public ArrayNode removeAll();

290

291

// Element access

292

public JsonNode get(int index);

293

public JsonNode path(int index);

294

public JsonNode path(String fieldName);

295

public boolean has(int index);

296

public boolean hasNonNull(int index);

297

298

// Container methods

299

public int size();

300

public boolean isEmpty();

301

public Iterator<JsonNode> elements();

302

public Iterator<JsonNode> iterator();

303

304

// Type information

305

public JsonNodeType getNodeType();

306

public boolean isArray();

307

308

// Copying

309

public ArrayNode deepCopy();

310

311

// Serialization

312

public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

313

public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException;

314

315

// String representation

316

public String toString();

317

}

318

```

319

320

## Value Nodes

321

322

Value nodes represent leaf values in the JSON tree (strings, numbers, booleans, null).

323

324

### TextNode

325

326

```java { .api }

327

public class TextNode extends ValueNode {

328

// Construction

329

public TextNode(String v);

330

public static TextNode valueOf(String v);

331

332

// Value access

333

public String textValue();

334

public String asText();

335

public String asText(String defaultValue);

336

public int asInt(int defaultValue);

337

public long asLong(long defaultValue);

338

public double asDouble(double defaultValue);

339

public boolean asBoolean(boolean defaultValue);

340

341

// Type information

342

public JsonNodeType getNodeType();

343

public boolean isTextual();

344

345

// Serialization

346

public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

347

348

// Comparison and string representation

349

public boolean equals(Object o);

350

public int hashCode();

351

public String toString();

352

}

353

```

354

355

### NumericNode

356

357

Base class for all numeric value nodes.

358

359

```java { .api }

360

public abstract class NumericNode extends ValueNode {

361

// Value access methods

362

public abstract Number numberValue();

363

public abstract int intValue();

364

public abstract long longValue();

365

public abstract double doubleValue();

366

public abstract BigDecimal decimalValue();

367

public abstract BigInteger bigIntegerValue();

368

369

// Type checking

370

public final boolean isNumber();

371

372

// Conversion methods

373

public abstract String asText();

374

public int asInt();

375

public int asInt(int defaultValue);

376

public long asLong();

377

public long asLong(long defaultValue);

378

public double asDouble();

379

public double asDouble(double defaultValue);

380

}

381

382

// Specific numeric node types

383

public class IntNode extends NumericNode {

384

public IntNode(int v);

385

public static IntNode valueOf(int i);

386

public JsonNodeType getNodeType();

387

public boolean isInt();

388

public boolean isIntegralNumber();

389

public Number numberValue();

390

public int intValue();

391

public long longValue();

392

public double doubleValue();

393

public float floatValue();

394

public short shortValue();

395

public BigDecimal decimalValue();

396

public BigInteger bigIntegerValue();

397

public String asText();

398

public boolean canConvertToInt();

399

public boolean canConvertToLong();

400

public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

401

}

402

403

public class LongNode extends NumericNode {

404

public LongNode(long v);

405

public static LongNode valueOf(long l);

406

// Similar methods as IntNode but for long values

407

}

408

409

public class DoubleNode extends NumericNode {

410

public DoubleNode(double v);

411

public static DoubleNode valueOf(double v);

412

// Similar methods as IntNode but for double values

413

}

414

415

public class DecimalNode extends NumericNode {

416

public DecimalNode(BigDecimal v);

417

public static DecimalNode valueOf(BigDecimal dec);

418

// Similar methods as IntNode but for BigDecimal values

419

}

420

421

public class BigIntegerNode extends NumericNode {

422

public BigIntegerNode(BigInteger v);

423

public static BigIntegerNode valueOf(BigInteger v);

424

// Similar methods as IntNode but for BigInteger values

425

}

426

427

public class FloatNode extends NumericNode {

428

public FloatNode(float v);

429

public static FloatNode valueOf(float v);

430

// Similar methods as IntNode but for float values

431

}

432

433

public class ShortNode extends NumericNode {

434

public ShortNode(short v);

435

public static ShortNode valueOf(short v);

436

// Similar methods as IntNode but for short values

437

}

438

```

439

440

### BooleanNode

441

442

```java { .api }

443

public class BooleanNode extends ValueNode {

444

// Singleton instances

445

public static final BooleanNode TRUE;

446

public static final BooleanNode FALSE;

447

448

// Factory methods

449

public static BooleanNode getTrue();

450

public static BooleanNode getFalse();

451

public static BooleanNode valueOf(boolean b);

452

453

// Value access

454

public boolean booleanValue();

455

public String asText();

456

public boolean asBoolean();

457

public boolean asBoolean(boolean defaultValue);

458

public int asInt(int defaultValue);

459

public long asLong(long defaultValue);

460

public double asDouble(double defaultValue);

461

462

// Type information

463

public JsonNodeType getNodeType();

464

public boolean isBoolean();

465

466

// Serialization

467

public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

468

469

// String representation

470

public String toString();

471

}

472

```

473

474

### NullNode and MissingNode

475

476

```java { .api }

477

public class NullNode extends ValueNode {

478

// Singleton instance

479

public static final NullNode instance;

480

481

// Factory method

482

public static NullNode getInstance();

483

484

// Type information

485

public JsonNodeType getNodeType();

486

public boolean isNull();

487

488

// Value access (all return null or defaults)

489

public String asText();

490

public String asText(String defaultValue);

491

public int asInt(int defaultValue);

492

public long asLong(long defaultValue);

493

public double asDouble(double defaultValue);

494

public boolean asBoolean(boolean defaultValue);

495

496

// Serialization

497

public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

498

499

// String representation

500

public String toString();

501

}

502

503

public final class MissingNode extends ValueNode {

504

// Singleton instance

505

private static final MissingNode instance;

506

507

// Factory method

508

public static MissingNode getInstance();

509

510

// Type information

511

public JsonNodeType getNodeType();

512

public boolean isMissingNode();

513

514

// Value access (all return defaults)

515

public String asText();

516

public String asText(String defaultValue);

517

public int asInt(int defaultValue);

518

public long asLong(long defaultValue);

519

public double asDouble(double defaultValue);

520

public boolean asBoolean(boolean defaultValue);

521

522

// Navigation (always returns MissingNode)

523

public JsonNode get(int index);

524

public JsonNode get(String fieldName);

525

public JsonNode path(String fieldName);

526

public JsonNode path(int index);

527

528

// String representation

529

public String toString();

530

}

531

```

532

533

### BinaryNode and POJONode

534

535

```java { .api }

536

public class BinaryNode extends ValueNode {

537

// Construction

538

public BinaryNode(byte[] data);

539

public BinaryNode(byte[] data, int offset, int length);

540

public static BinaryNode valueOf(byte[] data);

541

public static BinaryNode valueOf(byte[] data, int offset, int length);

542

543

// Value access

544

public byte[] binaryValue();

545

public byte[] getValue();

546

public String asText();

547

548

// Type information

549

public JsonNodeType getNodeType();

550

public boolean isBinary();

551

552

// Serialization

553

public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

554

555

// Comparison

556

public boolean equals(Object o);

557

public int hashCode();

558

}

559

560

public class POJONode extends ValueNode {

561

// Construction

562

public POJONode(Object pojo);

563

564

// Value access

565

public Object getPojo();

566

public byte[] binaryValue() throws IOException;

567

public String asText();

568

public boolean asBoolean(boolean defaultValue);

569

public int asInt(int defaultValue);

570

public long asLong(long defaultValue);

571

public double asDouble(double defaultValue);

572

573

// Type information

574

public JsonNodeType getNodeType();

575

public boolean isPojo();

576

577

// Serialization

578

public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException;

579

public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException;

580

581

// String representation

582

public String toString();

583

}

584

```

585

586

## JsonNodeFactory

587

588

Factory for creating JsonNode instances.

589

590

```java { .api }

591

public class JsonNodeFactory implements Serializable, JsonNodeCreator {

592

// Default instance

593

public static final JsonNodeFactory instance;

594

595

// Construction

596

public JsonNodeFactory();

597

public JsonNodeFactory(boolean bigDecimalExact);

598

599

// Configuration

600

public JsonNodeFactory enable(JsonNodeFeature f);

601

public JsonNodeFactory disable(JsonNodeFeature f);

602

public JsonNodeFactory with(JsonNodeFeature f, boolean state);

603

public boolean isEnabled(JsonNodeFeature f);

604

605

// Container nodes

606

public ObjectNode objectNode();

607

public ArrayNode arrayNode();

608

public ArrayNode arrayNode(int capacity);

609

610

// Value nodes

611

public NullNode nullNode();

612

public BooleanNode booleanNode(boolean v);

613

public TextNode textNode(String text);

614

public BinaryNode binaryNode(byte[] data);

615

public BinaryNode binaryNode(byte[] data, int offset, int length);

616

public POJONode pojoNode(Object pojo);

617

public RawValueNode rawValueNode(RawValue value);

618

619

// Numeric nodes

620

public NumericNode numberNode(byte v);

621

public NumericNode numberNode(short v);

622

public NumericNode numberNode(int v);

623

public NumericNode numberNode(long v);

624

public NumericNode numberNode(BigInteger v);

625

public NumericNode numberNode(float v);

626

public NumericNode numberNode(double v);

627

public NumericNode numberNode(BigDecimal v);

628

629

// Generic number node

630

public NumericNode numberNode(Number n);

631

}

632

633

public interface JsonNodeCreator {

634

// Value node creation methods (matching JsonNodeFactory)

635

ValueNode booleanNode(boolean v);

636

ValueNode nullNode();

637

NumericNode numberNode(byte v);

638

NumericNode numberNode(short v);

639

NumericNode numberNode(int v);

640

NumericNode numberNode(long v);

641

NumericNode numberNode(BigInteger v);

642

NumericNode numberNode(float v);

643

NumericNode numberNode(double v);

644

NumericNode numberNode(BigDecimal v);

645

ValueNode textNode(String text);

646

ValueNode binaryNode(byte[] data);

647

ValueNode binaryNode(byte[] data, int offset, int length);

648

ValueNode pojoNode(Object pojo);

649

ArrayNode arrayNode();

650

ObjectNode objectNode();

651

}

652

```

653

654

## Usage Examples

655

656

### Creating and Navigating Trees

657

658

```java

659

import com.fasterxml.jackson.databind.JsonNode;

660

import com.fasterxml.jackson.databind.ObjectMapper;

661

import com.fasterxml.jackson.databind.node.ObjectNode;

662

import com.fasterxml.jackson.databind.node.ArrayNode;

663

664

ObjectMapper mapper = new ObjectMapper();

665

666

// Parse JSON into tree

667

String json = "{\"name\":\"John\", \"age\":30, \"children\":[\"Jane\", \"Bob\"]}";

668

JsonNode root = mapper.readTree(json);

669

670

// Navigate tree

671

String name = root.get("name").asText();

672

int age = root.get("age").asInt();

673

JsonNode children = root.get("children");

674

675

// Check node types

676

if (root.isObject()) {

677

System.out.println("Root is an object");

678

}

679

if (children.isArray()) {

680

System.out.println("Children is an array with " + children.size() + " elements");

681

}

682

683

// Iterate through array

684

for (JsonNode child : children) {

685

System.out.println("Child: " + child.asText());

686

}

687

688

// Navigate with path (returns MissingNode if not found)

689

JsonNode address = root.path("address").path("street");

690

if (!address.isMissingNode()) {

691

System.out.println("Street: " + address.asText());

692

}

693

694

// Use JSON Pointer syntax

695

JsonNode firstChild = root.at("/children/0");

696

System.out.println("First child: " + firstChild.asText());

697

```

698

699

### Building Trees Programmatically

700

701

```java

702

import com.fasterxml.jackson.databind.node.JsonNodeFactory;

703

import com.fasterxml.jackson.databind.node.ObjectNode;

704

import com.fasterxml.jackson.databind.node.ArrayNode;

705

706

ObjectMapper mapper = new ObjectMapper();

707

JsonNodeFactory factory = mapper.getNodeFactory();

708

709

// Create object node

710

ObjectNode person = factory.objectNode();

711

person.put("name", "John");

712

person.put("age", 30);

713

person.put("active", true);

714

person.putNull("spouse");

715

716

// Create array node

717

ArrayNode hobbies = factory.arrayNode();

718

hobbies.add("reading");

719

hobbies.add("swimming");

720

hobbies.add("coding");

721

person.set("hobbies", hobbies);

722

723

// Create nested object

724

ObjectNode address = person.putObject("address");

725

address.put("street", "123 Main St");

726

address.put("city", "Springfield");

727

address.put("zip", "12345");

728

729

// Convert to JSON string

730

String json = mapper.writeValueAsString(person);

731

System.out.println(json);

732

```

733

734

### Modifying Existing Trees

735

736

```java

737

ObjectMapper mapper = new ObjectMapper();

738

String json = "{\"name\":\"John\", \"age\":30, \"hobbies\":[\"reading\"]}";

739

JsonNode root = mapper.readTree(json);

740

741

// Trees are immutable, but ObjectNode and ArrayNode allow modification

742

if (root.isObject()) {

743

ObjectNode obj = (ObjectNode) root;

744

745

// Update existing field

746

obj.put("age", 31);

747

748

// Add new field

749

obj.put("email", "john@example.com");

750

751

// Remove field

752

obj.remove("age");

753

754

// Modify array

755

JsonNode hobbiesNode = obj.get("hobbies");

756

if (hobbiesNode.isArray()) {

757

ArrayNode hobbies = (ArrayNode) hobbiesNode;

758

hobbies.add("swimming");

759

hobbies.insert(0, "cooking");

760

}

761

}

762

763

String updatedJson = mapper.writeValueAsString(root);

764

System.out.println(updatedJson);

765

```

766

767

### Tree Traversal and Search

768

769

```java

770

ObjectMapper mapper = new ObjectMapper();

771

String complexJson = """

772

{

773

"users": [

774

{

775

"name": "John",

776

"contact": {"email": "john@example.com"}

777

},

778

{

779

"name": "Jane",

780

"contact": {"email": "jane@example.com"}

781

}

782

]

783

}

784

""";

785

786

JsonNode root = mapper.readTree(complexJson);

787

788

// Find all values with specific field name

789

List<JsonNode> emails = new ArrayList<>();

790

root.findValues("email", emails);

791

for (JsonNode email : emails) {

792

System.out.println("Email: " + email.asText());

793

}

794

795

// Find values as text

796

List<String> emailTexts = root.findValuesAsText("email");

797

for (String email : emailTexts) {

798

System.out.println("Email text: " + email);

799

}

800

801

// Recursive traversal

802

void printAllValues(JsonNode node, String path) {

803

if (node.isValueNode()) {

804

System.out.println(path + ": " + node.asText());

805

} else if (node.isObject()) {

806

Iterator<Map.Entry<String, JsonNode>> fields = node.fields();

807

while (fields.hasNext()) {

808

Map.Entry<String, JsonNode> field = fields.next();

809

printAllValues(field.getValue(), path + "." + field.getKey());

810

}

811

} else if (node.isArray()) {

812

for (int i = 0; i < node.size(); i++) {

813

printAllValues(node.get(i), path + "[" + i + "]");

814

}

815

}

816

}

817

818

printAllValues(root, "root");

819

```

820

821

### Converting Between Tree and Objects

822

823

```java

824

ObjectMapper mapper = new ObjectMapper();

825

826

// POJO to tree

827

Person person = new Person("John", 30);

828

JsonNode tree = mapper.valueToTree(person);

829

830

// Tree to POJO

831

JsonNode personNode = tree;

832

Person converted = mapper.treeToValue(personNode, Person.class);

833

834

// Tree to different types

835

Map<String, Object> map = mapper.treeToValue(tree, Map.class);

836

String json = mapper.writeValueAsString(tree);

837

838

// Modify tree then convert

839

if (tree.isObject()) {

840

ObjectNode obj = (ObjectNode) tree;

841

obj.put("modified", true);

842

}

843

Person modified = mapper.treeToValue(tree, Person.class);

844

```

845

846

### Error Handling and Validation

847

848

```java

849

ObjectMapper mapper = new ObjectMapper();

850

851

// Safe navigation with path()

852

JsonNode root = mapper.readTree("{\"user\":{\"name\":\"John\"}}");

853

JsonNode email = root.path("user").path("contact").path("email");

854

if (email.isMissingNode()) {

855

System.out.println("Email not found");

856

} else {

857

System.out.println("Email: " + email.asText());

858

}

859

860

// Required field access (throws exception if missing)

861

try {

862

JsonNode requiredName = root.required("user").required("name");

863

System.out.println("Name: " + requiredName.asText());

864

} catch (IllegalArgumentException e) {

865

System.err.println("Required field missing: " + e.getMessage());

866

}

867

868

// Safe value extraction with defaults

869

String name = root.path("user").path("name").asText("Unknown");

870

int age = root.path("user").path("age").asInt(0);

871

boolean active = root.path("user").path("active").asBoolean(false);

872

```

873

874

## Types

875

876

```java { .api }

877

// Base container node class

878

public abstract class ContainerNode<T extends ContainerNode<T>> extends BaseJsonNode {

879

public abstract int size();

880

public abstract boolean isEmpty();

881

public abstract T removeAll();

882

public T setAll(Map<String, ? extends JsonNode> properties);

883

public T setAll(ObjectNode other);

884

}

885

886

// Base value node class

887

public abstract class ValueNode extends BaseJsonNode {

888

public final boolean isValueNode();

889

public final boolean isContainerNode();

890

public JsonNode get(int index);

891

public JsonNode get(String fieldName);

892

public JsonNode path(String fieldName);

893

public JsonNode path(int index);

894

}

895

896

// Base implementation class

897

public abstract class BaseJsonNode extends JsonNode implements Serializable {

898

// Common implementations for JsonNode abstract methods

899

}

900

901

// Tree traversing parser for converting trees to token streams

902

public class TreeTraversingParser extends ParserMinimalBase {

903

public TreeTraversingParser(JsonNode n);

904

public TreeTraversingParser(JsonNode n, ObjectCodec codec);

905

public JsonToken nextToken() throws IOException;

906

public JsonToken getCurrentToken();

907

public String getCurrentName() throws IOException;

908

public void close() throws IOException;

909

public boolean isClosed();

910

public JsonNode readValueAsTree() throws IOException;

911

public JsonLocation getCurrentLocation();

912

public String getText();

913

public char[] getTextCharacters() throws IOException;

914

public int getTextLength() throws IOException;

915

public int getTextOffset() throws IOException;

916

public Number getNumberValue() throws IOException;

917

public NumberType getNumberType() throws IOException;

918

public int getIntValue() throws IOException;

919

public long getLongValue() throws IOException;

920

public BigInteger getBigIntegerValue() throws IOException;

921

public float getFloatValue() throws IOException;

922

public double getDoubleValue() throws IOException;

923

public BigDecimal getDecimalValue() throws IOException;

924

public byte[] getBinaryValue(Base64Variant b64variant) throws IOException;

925

public String getValueAsString() throws IOException;

926

public String getValueAsString(String def) throws IOException;

927

public int getValueAsInt() throws IOException;

928

public int getValueAsInt(int def) throws IOException;

929

public long getValueAsLong() throws IOException;

930

public long getValueAsLong(long def) throws IOException;

931

public double getValueAsDouble() throws IOException;

932

public double getValueAsDouble(double def) throws IOException;

933

public boolean getValueAsBoolean() throws IOException;

934

public boolean getValueAsBoolean(boolean def) throws IOException;

935

}

936

937

// JSON Pointer implementation for navigation

938

public class JsonPointer implements Serializable {

939

public static final JsonPointer empty();

940

public static JsonPointer compile(String input) throws IllegalArgumentException;

941

public static JsonPointer valueOf(String input);

942

public static JsonPointer forPath(JsonStreamContext context);

943

public static JsonPointer forPath(JsonStreamContext context, boolean includeRoot);

944

945

public boolean matches();

946

public String getMatchingProperty();

947

public int getMatchingIndex();

948

public JsonPointer tail();

949

public JsonPointer head();

950

public JsonPointer last();

951

public JsonPointer parent();

952

public JsonPointer append(JsonPointer tail);

953

public JsonPointer append(String property);

954

public JsonPointer appendIndex(int index);

955

956

public String toString();

957

}

958

```