or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

codecs.mdcore-types.mdindex.mdio.mdjson.mdlegacy-api.mdtypes.md

json.mddocs/

0

# JSON Conversion

1

2

The BSON JSON support provides comprehensive conversion between BSON documents and JSON strings. It supports multiple JSON output formats including MongoDB Extended JSON, strict JSON, and shell format, with configurable settings for different use cases.

3

4

## JSON Reader

5

6

The `JsonReader` class reads JSON strings and converts them to BSON values.

7

8

```java { .api }

9

public class JsonReader extends AbstractBsonReader {

10

/**

11

* Constructs a new instance which reads from the given string.

12

* @param json a JSON string

13

*/

14

public JsonReader(String json);

15

16

/**

17

* Constructs a new instance which reads from the given Reader.

18

* @param reader a Reader containing JSON

19

*/

20

public JsonReader(Reader reader);

21

22

/**

23

* Constructs a new instance which reads from the given string using the given settings.

24

* @param json a JSON string

25

* @param settings the read settings

26

*/

27

public JsonReader(String json, JsonReaderSettings settings);

28

29

/**

30

* Constructs a new instance which reads from the given Reader using the given settings.

31

* @param reader a Reader containing JSON

32

* @param settings the read settings

33

*/

34

public JsonReader(Reader reader, JsonReaderSettings settings);

35

36

// Implementation of BsonReader interface

37

public BsonType readBsonType();

38

public String readName();

39

public void skipName();

40

public void skipValue();

41

public BsonBinary readBinaryData();

42

public boolean readBoolean();

43

public long readDateTime();

44

public double readDouble();

45

public int readInt32();

46

public long readInt64();

47

public Decimal128 readDecimal128();

48

public String readJavaScript();

49

public String readJavaScriptWithScope();

50

public void readMaxKey();

51

public void readMinKey();

52

public void readNull();

53

public ObjectId readObjectId();

54

public BsonRegularExpression readRegularExpression();

55

public String readString();

56

public String readSymbol();

57

public BsonTimestamp readTimestamp();

58

public void readUndefined();

59

public void readStartArray();

60

public void readEndArray();

61

public void readStartDocument();

62

public void readEndDocument();

63

public void close();

64

}

65

```

66

67

## JSON Writer

68

69

The `JsonWriter` class writes BSON values as JSON strings.

70

71

```java { .api }

72

public class JsonWriter extends AbstractBsonWriter {

73

/**

74

* Constructs a new instance which writes to the given writer.

75

* @param writer a Writer to write JSON to

76

*/

77

public JsonWriter(Writer writer);

78

79

/**

80

* Constructs a new instance which writes to the given writer and uses the given settings.

81

* @param writer a Writer to write JSON to

82

* @param settings the settings to apply to this writer

83

*/

84

public JsonWriter(Writer writer, JsonWriterSettings settings);

85

86

/**

87

* Constructs a new instance which writes to the given StringWriter.

88

* @param stringWriter a StringWriter to write JSON to

89

*/

90

public JsonWriter(StringWriter stringWriter);

91

92

/**

93

* Constructs a new instance which writes to the given StringWriter and uses the given settings.

94

* @param stringWriter a StringWriter to write JSON to

95

* @param settings the settings to apply to this writer

96

*/

97

public JsonWriter(StringWriter stringWriter, JsonWriterSettings settings);

98

99

// Implementation of BsonWriter interface

100

public void writeBinaryData(BsonBinary binary);

101

public void writeBoolean(boolean value);

102

public void writeDateTime(long value);

103

public void writeDouble(double value);

104

public void writeInt32(int value);

105

public void writeInt64(long value);

106

public void writeDecimal128(Decimal128 value);

107

public void writeJavaScript(String code);

108

public void writeJavaScriptWithScope(String code);

109

public void writeMaxKey();

110

public void writeMinKey();

111

public void writeName(String name);

112

public void writeNull();

113

public void writeObjectId(ObjectId objectId);

114

public void writeRegularExpression(BsonRegularExpression regularExpression);

115

public void writeString(String value);

116

public void writeSymbol(String value);

117

public void writeTimestamp(BsonTimestamp value);

118

public void writeUndefined();

119

public void writeStartArray();

120

public void writeEndArray();

121

public void writeStartDocument();

122

public void writeEndDocument();

123

public void flush();

124

public void close();

125

}

126

```

127

128

## JSON Reader Settings

129

130

```java { .api }

131

public final class JsonReaderSettings {

132

/**

133

* Gets the maximum length of JSON strings to parse.

134

* @return the maximum length

135

*/

136

public int getMaxLength();

137

138

/**

139

* Creates a builder for JsonReaderSettings.

140

* @return the builder

141

*/

142

public static Builder builder();

143

144

public static final class Builder {

145

/**

146

* Sets the maximum length of JSON strings to parse.

147

* @param maxLength the maximum length

148

* @return this

149

*/

150

public Builder maxLength(int maxLength);

151

152

/**

153

* Build the settings.

154

* @return the settings

155

*/

156

public JsonReaderSettings build();

157

}

158

}

159

```

160

161

## JSON Writer Settings

162

163

```java { .api }

164

public final class JsonWriterSettings {

165

/**

166

* Gets the output mode for JSON formatting.

167

* @return the output mode

168

*/

169

public JsonMode getOutputMode();

170

171

/**

172

* Gets whether output should be indented.

173

* @return true if output should be indented

174

*/

175

public boolean isIndent();

176

177

/**

178

* Gets the indent characters.

179

* @return the indent characters

180

*/

181

public String getIndentCharacters();

182

183

/**

184

* Gets the new line characters.

185

* @return the new line characters

186

*/

187

public String getNewLineCharacters();

188

189

/**

190

* Gets the maximum length of the JSON representation of a string.

191

* @return the maximum length

192

*/

193

public int getMaxLength();

194

195

/**

196

* Gets the DateTimeFormatter for formatting date/time values.

197

* @return the DateTimeFormatter

198

*/

199

public DateTimeFormatter getDateTimeFormatter();

200

201

/**

202

* Gets the converter for BsonBinary values.

203

* @return the converter

204

*/

205

public Converter<BsonBinary> getBinaryConverter();

206

207

/**

208

* Gets the converter for BsonBoolean values.

209

* @return the converter

210

*/

211

public Converter<BsonBoolean> getBooleanConverter();

212

213

/**

214

* Gets the converter for BsonDateTime values.

215

* @return the converter

216

*/

217

public Converter<BsonDateTime> getDateTimeConverter();

218

219

/**

220

* Gets the converter for BsonDecimal128 values.

221

* @return the converter

222

*/

223

public Converter<BsonDecimal128> getDecimal128Converter();

224

225

/**

226

* Gets the converter for BsonDouble values.

227

* @return the converter

228

*/

229

public Converter<BsonDouble> getDoubleConverter();

230

231

/**

232

* Gets the converter for BsonInt32 values.

233

* @return the converter

234

*/

235

public Converter<BsonInt32> getInt32Converter();

236

237

/**

238

* Gets the converter for BsonInt64 values.

239

* @return the converter

240

*/

241

public Converter<BsonInt64> getInt64Converter();

242

243

/**

244

* Gets the converter for BsonObjectId values.

245

* @return the converter

246

*/

247

public Converter<BsonObjectId> getObjectIdConverter();

248

249

/**

250

* Gets the converter for BsonString values.

251

* @return the converter

252

*/

253

public Converter<BsonString> getStringConverter();

254

255

/**

256

* Creates a builder for JsonWriterSettings.

257

* @return the builder

258

*/

259

public static Builder builder();

260

261

public static final class Builder {

262

/**

263

* Sets the output mode.

264

* @param outputMode the output mode

265

* @return this

266

*/

267

public Builder outputMode(JsonMode outputMode);

268

269

/**

270

* Sets whether output should be indented.

271

* @param indent true if output should be indented

272

* @return this

273

*/

274

public Builder indent(boolean indent);

275

276

/**

277

* Sets the indent characters.

278

* @param indentCharacters the indent characters

279

* @return this

280

*/

281

public Builder indentCharacters(String indentCharacters);

282

283

/**

284

* Sets the new line characters.

285

* @param newLineCharacters the new line characters

286

* @return this

287

*/

288

public Builder newLineCharacters(String newLineCharacters);

289

290

/**

291

* Sets the maximum length of the JSON representation.

292

* @param maxLength the maximum length

293

* @return this

294

*/

295

public Builder maxLength(int maxLength);

296

297

/**

298

* Sets the DateTimeFormatter for date/time formatting.

299

* @param dateTimeFormatter the DateTimeFormatter

300

* @return this

301

*/

302

public Builder dateTimeFormatter(DateTimeFormatter dateTimeFormatter);

303

304

/**

305

* Sets the converter for BsonBinary values.

306

* @param binaryConverter the converter

307

* @return this

308

*/

309

public Builder binaryConverter(Converter<BsonBinary> binaryConverter);

310

311

/**

312

* Sets the converter for BsonDateTime values.

313

* @param dateTimeConverter the converter

314

* @return this

315

*/

316

public Builder dateTimeConverter(Converter<BsonDateTime> dateTimeConverter);

317

318

/**

319

* Sets the converter for BsonDecimal128 values.

320

* @param decimal128Converter the converter

321

* @return this

322

*/

323

public Builder decimal128Converter(Converter<BsonDecimal128> decimal128Converter);

324

325

/**

326

* Sets the converter for BsonObjectId values.

327

* @param objectIdConverter the converter

328

* @return this

329

*/

330

public Builder objectIdConverter(Converter<BsonObjectId> objectIdConverter);

331

332

/**

333

* Build the settings.

334

* @return the settings

335

*/

336

public JsonWriterSettings build();

337

}

338

}

339

```

340

341

## JSON Output Modes

342

343

```java { .api }

344

public enum JsonMode {

345

/**

346

* Strict mode produces output that conforms to the JSON RFC.

347

* For BSON types that do not have a JSON equivalent, it uses the "canonical" extended JSON representation.

348

*/

349

STRICT,

350

351

/**

352

* Extended mode produces output that conforms to the MongoDB Extended JSON specification.

353

* This is the most compact representation while preserving type information.

354

*/

355

EXTENDED,

356

357

/**

358

* Relaxed mode produces output that is more readable and JavaScript-compatible.

359

* Some BSON type information may be lost.

360

*/

361

RELAXED,

362

363

/**

364

* Shell mode produces output that can be parsed by the MongoDB shell.

365

*/

366

SHELL

367

}

368

```

369

370

## JSON Converters

371

372

```java { .api }

373

public interface Converter<T> {

374

/**

375

* Convert the given value to a string.

376

* @param value the value to convert

377

* @return the string representation

378

*/

379

void convert(T value, StrictJsonWriter writer);

380

}

381

382

public final class StrictJsonWriter {

383

/**

384

* Writes a raw JSON value.

385

* @param json the JSON string

386

*/

387

public void writeRaw(String json);

388

389

/**

390

* Writes a string value.

391

* @param value the string value

392

*/

393

public void writeString(String value);

394

395

/**

396

* Writes a number value.

397

* @param value the number value

398

*/

399

public void writeNumber(String value);

400

401

/**

402

* Writes a boolean value.

403

* @param value the boolean value

404

*/

405

public void writeBoolean(boolean value);

406

407

/**

408

* Writes a null value.

409

*/

410

public void writeNull();

411

412

/**

413

* Writes the start of an object.

414

*/

415

public void writeStartObject();

416

417

/**

418

* Writes the end of an object.

419

*/

420

public void writeEndObject();

421

422

/**

423

* Writes the start of an array.

424

*/

425

public void writeStartArray();

426

427

/**

428

* Writes the end of an array.

429

*/

430

public void writeEndArray();

431

432

/**

433

* Writes a field name.

434

* @param name the field name

435

*/

436

public void writeName(String name);

437

}

438

```

439

440

## Built-in JSON Converters

441

442

```java { .api }

443

public final class JsonConverters {

444

/**

445

* A converter that writes ObjectId values in strict JSON format.

446

*/

447

public static final Converter<BsonObjectId> OBJECT_ID_CONVERTER =

448

(value, writer) -> {

449

writer.writeStartObject();

450

writer.writeName("$oid");

451

writer.writeString(value.getValue().toHexString());

452

writer.writeEndObject();

453

};

454

455

/**

456

* A converter that writes DateTime values in strict JSON format.

457

*/

458

public static final Converter<BsonDateTime> DATE_TIME_CONVERTER =

459

(value, writer) -> {

460

writer.writeStartObject();

461

writer.writeName("$date");

462

writer.writeNumber(Long.toString(value.getValue()));

463

writer.writeEndObject();

464

};

465

466

/**

467

* A converter that writes Binary values in strict JSON format.

468

*/

469

public static final Converter<BsonBinary> BINARY_CONVERTER =

470

(value, writer) -> {

471

writer.writeStartObject();

472

writer.writeName("$binary");

473

writer.writeStartObject();

474

writer.writeName("base64");

475

writer.writeString(Base64.getEncoder().encodeToString(value.getData()));

476

writer.writeName("subType");

477

writer.writeString(String.format("%02x", value.getType()));

478

writer.writeEndObject();

479

writer.writeEndObject();

480

};

481

482

/**

483

* A converter that writes Decimal128 values in strict JSON format.

484

*/

485

public static final Converter<BsonDecimal128> DECIMAL128_CONVERTER =

486

(value, writer) -> {

487

writer.writeStartObject();

488

writer.writeName("$numberDecimal");

489

writer.writeString(value.getValue().toString());

490

writer.writeEndObject();

491

};

492

}

493

```

494

495

## Usage Examples

496

497

### Basic JSON Conversion

498

499

```java

500

import org.bson.*;

501

import org.bson.json.*;

502

503

// Create a BSON document

504

BsonDocument document = new BsonDocument()

505

.append("name", new BsonString("John Doe"))

506

.append("age", new BsonInt32(30))

507

.append("_id", new BsonObjectId(new ObjectId()))

508

.append("created", new BsonDateTime(System.currentTimeMillis()));

509

510

// Convert to JSON with different modes

511

String strictJson = document.toJson(JsonWriterSettings.builder()

512

.outputMode(JsonMode.STRICT)

513

.build());

514

515

String extendedJson = document.toJson(JsonWriterSettings.builder()

516

.outputMode(JsonMode.EXTENDED)

517

.build());

518

519

String relaxedJson = document.toJson(JsonWriterSettings.builder()

520

.outputMode(JsonMode.RELAXED)

521

.build());

522

523

// Parse JSON back to BSON

524

BsonDocument parsed = BsonDocument.parse(strictJson);

525

```

526

527

### Custom JSON Formatting

528

529

```java

530

import org.bson.json.*;

531

import java.time.format.DateTimeFormatter;

532

533

JsonWriterSettings customSettings = JsonWriterSettings.builder()

534

.outputMode(JsonMode.EXTENDED)

535

.indent(true)

536

.indentCharacters(" ")

537

.newLineCharacters("\n")

538

.dateTimeFormatter(DateTimeFormatter.ISO_INSTANT)

539

.build();

540

541

String formattedJson = document.toJson(customSettings);

542

```

543

544

### Streaming JSON Processing

545

546

```java

547

import org.bson.json.*;

548

import java.io.*;

549

550

// Write JSON using JsonWriter

551

StringWriter stringWriter = new StringWriter();

552

JsonWriter jsonWriter = new JsonWriter(stringWriter,

553

JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build());

554

555

jsonWriter.writeStartDocument();

556

jsonWriter.writeString("name", "Alice");

557

jsonWriter.writeInt32("age", 25);

558

jsonWriter.writeStartArray("hobbies");

559

jsonWriter.writeString("reading");

560

jsonWriter.writeString("coding");

561

jsonWriter.writeEndArray();

562

jsonWriter.writeEndDocument();

563

jsonWriter.close();

564

565

String json = stringWriter.toString();

566

567

// Read JSON using JsonReader

568

JsonReader jsonReader = new JsonReader(json);

569

jsonReader.readStartDocument();

570

while (jsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {

571

String fieldName = jsonReader.readName();

572

switch (jsonReader.getCurrentBsonType()) {

573

case STRING:

574

String stringValue = jsonReader.readString();

575

break;

576

case INT32:

577

int intValue = jsonReader.readInt32();

578

break;

579

case ARRAY:

580

jsonReader.readStartArray();

581

while (jsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {

582

String arrayItem = jsonReader.readString();

583

}

584

jsonReader.readEndArray();

585

break;

586

}

587

}

588

jsonReader.readEndDocument();

589

jsonReader.close();

590

```

591

592

### Custom Type Converters

593

594

```java

595

import org.bson.json.*;

596

597

// Custom converter for ObjectId that writes just the hex string

598

Converter<BsonObjectId> simpleObjectIdConverter = (value, writer) -> {

599

writer.writeString(value.getValue().toHexString());

600

};

601

602

// Custom converter for DateTime that uses ISO format

603

Converter<BsonDateTime> isoDateConverter = (value, writer) -> {

604

Instant instant = Instant.ofEpochMilli(value.getValue());

605

writer.writeString(instant.toString());

606

};

607

608

JsonWriterSettings customConverterSettings = JsonWriterSettings.builder()

609

.outputMode(JsonMode.EXTENDED)

610

.objectIdConverter(simpleObjectIdConverter)

611

.dateTimeConverter(isoDateConverter)

612

.build();

613

614

String customJson = document.toJson(customConverterSettings);

615

```

616

617

### Reading Large JSON Documents

618

619

```java

620

import org.bson.json.*;

621

import java.io.*;

622

623

// Process large JSON documents with streaming

624

try (FileReader fileReader = new FileReader("large-document.json");

625

JsonReader jsonReader = new JsonReader(fileReader)) {

626

627

jsonReader.readStartDocument();

628

while (jsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {

629

String fieldName = jsonReader.readName();

630

631

if (fieldName.equals("items")) {

632

jsonReader.readStartArray();

633

while (jsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {

634

// Process each item without loading entire array into memory

635

jsonReader.readStartDocument();

636

// ... read item fields

637

jsonReader.readEndDocument();

638

}

639

jsonReader.readEndArray();

640

} else {

641

jsonReader.skipValue(); // Skip unknown fields

642

}

643

}

644

jsonReader.readEndDocument();

645

}

646

```

647

648

### Working with Different JSON Modes

649

650

```java

651

BsonDocument doc = new BsonDocument()

652

.append("_id", new BsonObjectId(new ObjectId()))

653

.append("date", new BsonDateTime(System.currentTimeMillis()))

654

.append("decimal", new BsonDecimal128(new Decimal128("123.45")))

655

.append("binary", new BsonBinary(BsonBinarySubType.GENERIC, "Hello".getBytes()));

656

657

// Strict JSON (RFC compliant)

658

String strict = doc.toJson(JsonWriterSettings.builder()

659

.outputMode(JsonMode.STRICT).build());

660

// {"_id": {"$oid": "..."}, "date": {"$date": 1234567890}, ...}

661

662

// Extended JSON (MongoDB extended format)

663

String extended = doc.toJson(JsonWriterSettings.builder()

664

.outputMode(JsonMode.EXTENDED).build());

665

// {"_id": {"$oid": "..."}, "date": {"$date": "2023-..."}, ...}

666

667

// Relaxed JSON (more readable, some type info lost)

668

String relaxed = doc.toJson(JsonWriterSettings.builder()

669

.outputMode(JsonMode.RELAXED).build());

670

// {"_id": {"$oid": "..."}, "date": "2023-...", "decimal": 123.45, ...}

671

672

// Shell JSON (MongoDB shell compatible)

673

String shell = doc.toJson(JsonWriterSettings.builder()

674

.outputMode(JsonMode.SHELL).build());

675

// {_id: ObjectId("..."), date: ISODate("..."), ...}

676

```