or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdannotations.mdcore-operations.mddata-structures.mdindex.mdreader-writer.md

advanced-features.mddocs/

0

# Advanced Features

1

2

High-performance features including JSONB binary format, JSONPath queries, schema validation, and custom filters. These capabilities extend beyond basic JSON processing to provide enterprise-grade functionality.

3

4

## Capabilities

5

6

### JSONB Binary Format

7

8

High-performance binary JSON format optimized for speed and size, ideal for data transmission and storage.

9

10

```java { .api }

11

/**

12

* JSONB binary format operations

13

*/

14

public class JSONB {

15

16

/**

17

* Convert object to JSONB binary format

18

* @param object Object to serialize

19

* @return JSONB bytes

20

*/

21

public static byte[] toBytes(Object object);

22

23

/**

24

* Convert object to JSONB with symbol table

25

* @param object Object to serialize

26

* @param symbolTable Symbol table for optimization

27

* @return JSONB bytes

28

*/

29

public static byte[] toBytes(Object object, SymbolTable symbolTable);

30

31

/**

32

* Parse JSONB bytes to object

33

* @param bytes JSONB binary data

34

* @return Parsed object

35

*/

36

public static Object parseObject(byte[] bytes);

37

38

/**

39

* Parse JSONB bytes with offset and length

40

* @param bytes JSONB binary data

41

* @param offset Starting offset

42

* @param length Data length

43

* @return Parsed object

44

*/

45

public static Object parseObject(byte[] bytes, int offset, int length);

46

47

/**

48

* Parse JSONB bytes to specific class

49

* @param bytes JSONB binary data

50

* @param clazz Target class type

51

* @return Instance of specified class

52

*/

53

public static <T> T parseObject(byte[] bytes, Class<T> clazz);

54

55

/**

56

* Parse JSONB bytes to specific class with offset

57

* @param bytes JSONB binary data

58

* @param offset Starting offset

59

* @param length Data length

60

* @param clazz Target class type

61

* @return Instance of specified class

62

*/

63

public static <T> T parseObject(byte[] bytes, int offset, int length, Class<T> clazz);

64

65

/**

66

* Parse JSONB bytes with Type reference

67

* @param bytes JSONB binary data

68

* @param type Target type

69

* @return Instance of specified type

70

*/

71

public static <T> T parseObject(byte[] bytes, Type type);

72

73

/**

74

* Parse JSONB to JSONArray

75

* @param bytes JSONB binary data

76

* @return JSONArray instance

77

*/

78

public static JSONArray parseArray(byte[] bytes);

79

80

/**

81

* Parse JSONB to typed List

82

* @param bytes JSONB binary data

83

* @param clazz Element class type

84

* @return List of specified element type

85

*/

86

public static <T> List<T> parseArray(byte[] bytes, Class<T> clazz);

87

88

/**

89

* Debug JSONB binary format

90

* @param bytes JSONB binary data

91

* @return Human-readable format description

92

*/

93

public static String dump(byte[] bytes);

94

95

/**

96

* Extract type information from JSONB

97

* @param bytes JSONB binary data

98

* @return Type name string

99

*/

100

public static String typeName(byte[] bytes);

101

102

/**

103

* Check if bytes contain valid JSONB data

104

* @param bytes Binary data to check

105

* @return true if valid JSONB format

106

*/

107

public static boolean isValid(byte[] bytes);

108

109

/**

110

* Create symbol table from objects for optimization

111

* @param objects Objects to analyze for symbols

112

* @return SymbolTable for reuse

113

*/

114

public static SymbolTable symbolTable(Object... objects);

115

}

116

```

117

118

### JSONPath Queries

119

120

Advanced path-based JSON data extraction and manipulation using JSONPath expressions.

121

122

```java { .api }

123

/**

124

* JSONPath query operations

125

*/

126

public class JSONPath {

127

128

/**

129

* Extract values from JSON string using path expression

130

* @param json JSON string

131

* @param path JSONPath expression

132

* @return Extracted value(s)

133

*/

134

public static Object extract(String json, String path);

135

136

/**

137

* Evaluate path expression against object

138

* @param rootObject Root object to query

139

* @param path JSONPath expression

140

* @return Query result

141

*/

142

public static Object eval(Object rootObject, String path);

143

144

/**

145

* Set value at specified path in JSON string

146

* @param json JSON string

147

* @param path JSONPath expression

148

* @param value Value to set

149

* @return Modified JSON string

150

*/

151

public static String set(String json, String path, Object value);

152

153

/**

154

* Create compiled JSONPath instance for reuse

155

* @param path JSONPath expression

156

* @return Compiled JSONPath instance

157

*/

158

public static JSONPath of(String path);

159

160

/**

161

* Extract values using compiled path

162

* @param rootObject Root object to query

163

* @return Query result

164

*/

165

public Object extract(Object rootObject);

166

167

/**

168

* Set value using compiled path

169

* @param rootObject Root object to modify

170

* @param value Value to set

171

*/

172

public void set(Object rootObject, Object value);

173

174

/**

175

* Check if path exists in object

176

* @param rootObject Root object to check

177

* @return true if path exists

178

*/

179

public boolean contains(Object rootObject);

180

181

/**

182

* Remove value at path from object

183

* @param rootObject Root object to modify

184

* @return Removed value

185

*/

186

public Object remove(Object rootObject);

187

188

/**

189

* Get all matching paths in object

190

* @param rootObject Root object to analyze

191

* @return Set of matching paths

192

*/

193

public Set<String> paths(Object rootObject);

194

195

/**

196

* Set callback for path evaluation

197

* @param callback Callback to invoke during evaluation

198

*/

199

public void setCallback(PathCallback callback);

200

}

201

202

/**

203

* JSONPath configuration features

204

*/

205

public enum JSONPath.Feature {

206

/** Always return results as a list */

207

AlwaysReturnList,

208

209

/** Suppress exceptions during path evaluation */

210

SuppressExceptions,

211

212

/** Use native object types instead of JSON types */

213

UseNativeObject

214

}

215

```

216

217

### Schema Validation

218

219

JSON Schema validation capabilities for ensuring data integrity and structure compliance.

220

221

```java { .api }

222

/**

223

* Base JSON Schema validation

224

*/

225

public abstract class JSONSchema {

226

227

/**

228

* Validate object against schema

229

* @param object Object to validate

230

* @return Validation result

231

*/

232

public ValidateResult validate(Object object);

233

234

/**

235

* Check if object is valid against schema

236

* @param object Object to validate

237

* @return true if valid

238

*/

239

public boolean isValid(Object object);

240

241

/**

242

* Parse schema from JSON string

243

* @param schema Schema definition

244

* @return JSONSchema instance

245

*/

246

public static JSONSchema parse(String schema);

247

}

248

249

/**

250

* Object schema validation

251

*/

252

public class ObjectSchema extends JSONSchema {

253

254

/**

255

* Set required properties

256

* @param properties Array of required property names

257

* @return This schema for chaining

258

*/

259

public ObjectSchema required(String... properties);

260

261

/**

262

* Set property schemas

263

* @param name Property name

264

* @param schema Property schema

265

* @return This schema for chaining

266

*/

267

public ObjectSchema property(String name, JSONSchema schema);

268

}

269

270

/**

271

* String schema with pattern validation

272

*/

273

public class StringSchema extends JSONSchema {

274

275

/**

276

* Set minimum length constraint

277

* @param minLength Minimum string length

278

* @return This schema for chaining

279

*/

280

public StringSchema minLength(int minLength);

281

282

/**

283

* Set maximum length constraint

284

* @param maxLength Maximum string length

285

* @return This schema for chaining

286

*/

287

public StringSchema maxLength(int maxLength);

288

289

/**

290

* Set pattern constraint

291

* @param pattern Regular expression pattern

292

* @return This schema for chaining

293

*/

294

public StringSchema pattern(String pattern);

295

}

296

297

/**

298

* Validation result container

299

*/

300

public class ValidateResult {

301

302

/**

303

* Check if validation passed

304

* @return true if valid

305

*/

306

public boolean isSuccess();

307

308

/**

309

* Get validation error message

310

* @return Error message or null if valid

311

*/

312

public String getMessage();

313

}

314

```

315

316

### Custom Filters

317

318

Extensible filter system for transforming data during serialization and deserialization.

319

320

```java { .api }

321

/**

322

* Base filter interface

323

*/

324

public interface Filter {

325

}

326

327

/**

328

* Transform property names during serialization

329

*/

330

public interface NameFilter extends Filter {

331

332

/**

333

* Transform property name

334

* @param object Source object

335

* @param name Original property name

336

* @param value Property value

337

* @return Transformed property name

338

*/

339

String process(Object object, String name, Object value);

340

}

341

342

/**

343

* Transform property values during serialization

344

*/

345

public interface ValueFilter extends Filter {

346

347

/**

348

* Transform property value

349

* @param object Source object

350

* @param name Property name

351

* @param value Original property value

352

* @return Transformed property value

353

*/

354

Object process(Object object, String name, Object value);

355

}

356

357

/**

358

* Control property inclusion during serialization

359

*/

360

public interface PropertyFilter extends Filter {

361

362

/**

363

* Determine if property should be included

364

* @param object Source object

365

* @param name Property name

366

* @param value Property value

367

* @return true to include property

368

*/

369

boolean apply(Object object, String name, Object value);

370

}

371

372

/**

373

* Pre-processing filter executed before serialization

374

*/

375

public interface BeforeFilter extends Filter {

376

377

/**

378

* Process object before serialization

379

* @param object Source object

380

*/

381

void writeBefore(Object object);

382

}

383

384

/**

385

* Post-processing filter executed after serialization

386

*/

387

public interface AfterFilter extends Filter {

388

389

/**

390

* Process object after serialization

391

* @param object Source object

392

*/

393

void writeAfter(Object object);

394

}

395

```

396

397

**Usage Examples:**

398

399

```java

400

import com.alibaba.fastjson2.*;

401

import com.alibaba.fastjson2.schema.*;

402

import com.alibaba.fastjson2.filter.*;

403

404

// JSONB Binary Format

405

User user = new User("John", 30);

406

407

// Convert to binary

408

byte[] jsonbBytes = JSONB.toBytes(user);

409

System.out.println("JSONB size: " + jsonbBytes.length); // Much smaller than JSON

410

411

// Parse from binary

412

User parsedUser = JSONB.parseObject(jsonbBytes, User.class);

413

414

// Debug binary format

415

String dump = JSONB.dump(jsonbBytes);

416

System.out.println("JSONB structure: " + dump);

417

418

// JSONPath Queries

419

String json = """

420

{

421

"users": [

422

{"name": "John", "age": 30, "city": "NYC"},

423

{"name": "Jane", "age": 25, "city": "SF"},

424

{"name": "Bob", "age": 35, "city": "LA"}

425

]

426

}

427

""";

428

429

// Basic path extraction

430

Object allUsers = JSONPath.extract(json, "$.users");

431

Object firstUser = JSONPath.extract(json, "$.users[0]");

432

Object allNames = JSONPath.extract(json, "$.users[*].name");

433

434

// Filtered queries

435

Object adults = JSONPath.extract(json, "$.users[?(@.age >= 30)]");

436

Object nycUsers = JSONPath.extract(json, "$.users[?(@.city == 'NYC')]");

437

438

// Compiled paths for reuse

439

JSONPath namePath = JSONPath.of("$.users[*].name");

440

List<String> names = (List<String>) namePath.extract(JSON.parseObject(json));

441

442

// Path modification

443

String modified = JSONPath.set(json, "$.users[0].age", 31);

444

445

// Schema Validation

446

String schemaJson = """

447

{

448

"type": "object",

449

"required": ["name", "email"],

450

"properties": {

451

"name": {"type": "string", "minLength": 2},

452

"email": {"type": "string", "pattern": "^[^@]+@[^@]+\\.[^@]+$"},

453

"age": {"type": "integer", "minimum": 0}

454

}

455

}

456

""";

457

458

JSONSchema schema = JSONSchema.parse(schemaJson);

459

460

// Validate objects

461

User validUser = new User("John", "john@example.com", 30);

462

User invalidUser = new User("", "invalid-email", -5);

463

464

ValidateResult validResult = schema.validate(validUser);

465

ValidateResult invalidResult = schema.validate(invalidUser);

466

467

System.out.println("Valid user: " + validResult.isSuccess()); // true

468

System.out.println("Invalid user: " + invalidResult.isSuccess()); // false

469

System.out.println("Error: " + invalidResult.getMessage());

470

471

// Custom Filters

472

// Name filter to transform property names

473

NameFilter snakeCaseFilter = (object, name, value) -> {

474

return name.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();

475

};

476

477

// Value filter to mask sensitive data

478

ValueFilter passwordFilter = (object, name, value) -> {

479

if ("password".equals(name)) {

480

return "***masked***";

481

}

482

return value;

483

};

484

485

// Property filter to exclude null values

486

PropertyFilter nullFilter = (object, name, value) -> value != null;

487

488

// Apply filters during serialization

489

JSON.config(snakeCaseFilter, passwordFilter, nullFilter);

490

491

User userWithPassword = new User("John", "secret123");

492

userWithPassword.setEmail(null);

493

494

String filteredJson = JSON.toJSONString(userWithPassword);

495

// Result: {"user_name":"John","password":"***masked***"}

496

// Note: email field excluded because it's null

497

498

// Stream processing for large datasets

499

try (InputStream inputStream = new FileInputStream("large-data.json")) {

500

StreamReader reader = new StreamReader(inputStream);

501

502

reader.readObject((path, value) -> {

503

if (path.endsWith(".user.name")) {

504

System.out.println("Found user: " + value);

505

}

506

});

507

}

508

```

509

510

### Advanced JSONPath Examples

511

512

```java

513

// Complex path expressions

514

String complexJson = """

515

{

516

"store": {

517

"book": [

518

{"category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95},

519

{"category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99},

520

{"category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "price": 8.99}

521

],

522

"bicycle": {"color": "red", "price": 19.95}

523

}

524

}

525

""";

526

527

// Get all book prices

528

Object bookPrices = JSONPath.extract(complexJson, "$.store.book[*].price");

529

530

// Get books cheaper than $10

531

Object cheapBooks = JSONPath.extract(complexJson, "$.store.book[?(@.price < 10)]");

532

533

// Get fiction books

534

Object fictionBooks = JSONPath.extract(complexJson, "$.store.book[?(@.category == 'fiction')]");

535

536

// Get all prices (books and bicycle)

537

Object allPrices = JSONPath.extract(complexJson, "$..price");

538

539

// Get last book

540

Object lastBook = JSONPath.extract(complexJson, "$.store.book[-1]");

541

542

// Complex filtering with multiple conditions

543

Object expensiveFiction = JSONPath.extract(complexJson,

544

"$.store.book[?(@.category == 'fiction' && @.price > 10)]");

545

```

546

547

### Schema Validation Examples

548

549

```java

550

// Programmatic schema creation

551

ObjectSchema userSchema = new ObjectSchema()

552

.required("name", "email")

553

.property("name", new StringSchema().minLength(2).maxLength(50))

554

.property("email", new StringSchema().pattern("^[^@]+@[^@]+\\.[^@]+$"))

555

.property("age", new IntegerSchema().minimum(0).maximum(150));

556

557

// Array schema

558

ArraySchema usersSchema = new ArraySchema()

559

.items(userSchema)

560

.minItems(1)

561

.maxItems(100);

562

563

// Nested object validation

564

ObjectSchema addressSchema = new ObjectSchema()

565

.required("street", "city")

566

.property("street", new StringSchema().minLength(1))

567

.property("city", new StringSchema().minLength(1))

568

.property("zipCode", new StringSchema().pattern("\\d{5}(-\\d{4})?"));

569

570

ObjectSchema userWithAddressSchema = new ObjectSchema()

571

.required("name", "address")

572

.property("name", new StringSchema())

573

.property("address", addressSchema);

574

```