or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

exception-handling.mdfactory-configuration.mdfeatures-configuration.mdindex.mdjson-generation.mdjson-parsing.mdutilities-advanced.md

json-generation.mddocs/

0

# JSON Generation

1

2

JsonGenerator provides streaming JSON generation with support for all JSON data types, pretty printing, and configurable output features. It writes JSON content incrementally with efficient memory usage and proper escaping.

3

4

## Core Generation API

5

6

### Structure Methods

7

8

```java { .api }

9

public abstract void writeStartObject() throws IOException;

10

public abstract void writeEndObject() throws IOException;

11

public abstract void writeStartArray() throws IOException;

12

public abstract void writeEndArray() throws IOException;

13

public void writeStartObject(Object forValue) throws IOException;

14

public void writeStartArray(Object forValue) throws IOException;

15

public void writeStartArray(Object forValue, int size) throws IOException;

16

```

17

18

### Field Names

19

20

```java { .api }

21

public abstract void writeFieldName(String name) throws IOException;

22

public abstract void writeFieldName(SerializableString name) throws IOException;

23

public void writeFieldId(long id) throws IOException;

24

```

25

26

### Value Methods

27

28

```java { .api }

29

public abstract void writeString(String text) throws IOException;

30

public abstract void writeString(char[] text, int offset, int len) throws IOException;

31

public abstract void writeString(SerializableString text) throws IOException;

32

public void writeString(Reader reader, int len) throws IOException;

33

34

public abstract void writeRawUTF8String(byte[] text, int offset, int length) throws IOException;

35

public abstract void writeUTF8String(byte[] text, int offset, int length) throws IOException;

36

37

public abstract void writeRaw(String text) throws IOException;

38

public abstract void writeRaw(String text, int offset, int len) throws IOException;

39

public abstract void writeRaw(char[] text, int offset, int len) throws IOException;

40

public abstract void writeRaw(char c) throws IOException;

41

public void writeRawValue(String text) throws IOException;

42

```

43

44

### Numeric Values

45

46

```java { .api }

47

public abstract void writeNumber(short v) throws IOException;

48

public abstract void writeNumber(int v) throws IOException;

49

public abstract void writeNumber(long v) throws IOException;

50

public abstract void writeNumber(BigInteger v) throws IOException;

51

public abstract void writeNumber(double v) throws IOException;

52

public abstract void writeNumber(float v) throws IOException;

53

public abstract void writeNumber(BigDecimal v) throws IOException;

54

public abstract void writeNumber(String encodedValue) throws IOException;

55

```

56

57

### Boolean and Null

58

59

```java { .api }

60

public abstract void writeBoolean(boolean state) throws IOException;

61

public abstract void writeNull() throws IOException;

62

```

63

64

### Binary Data

65

66

```java { .api }

67

public abstract void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException;

68

public void writeBinary(byte[] data, int offset, int len) throws IOException;

69

public void writeBinary(byte[] data) throws IOException;

70

public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) throws IOException;

71

```

72

73

## Convenience Methods

74

75

### Field-Value Pairs

76

77

```java { .api }

78

public void writeStringField(String fieldName, String value) throws IOException;

79

public void writeBooleanField(String fieldName, boolean value) throws IOException;

80

public void writeNullField(String fieldName) throws IOException;

81

public void writeNumberField(String fieldName, short value) throws IOException;

82

public void writeNumberField(String fieldName, int value) throws IOException;

83

public void writeNumberField(String fieldName, long value) throws IOException;

84

public void writeNumberField(String fieldName, BigInteger value) throws IOException;

85

public void writeNumberField(String fieldName, float value) throws IOException;

86

public void writeNumberField(String fieldName, double value) throws IOException;

87

public void writeNumberField(String fieldName, BigDecimal value) throws IOException;

88

public void writeBinaryField(String fieldName, byte[] data) throws IOException;

89

public void writeArrayFieldStart(String fieldName) throws IOException;

90

public void writeObjectFieldStart(String fieldName) throws IOException;

91

```

92

93

### Object Field Methods

94

95

```java { .api }

96

public void writeObjectField(String fieldName, Object pojo) throws IOException;

97

public void writeTree(TreeNode rootNode) throws IOException;

98

```

99

100

## Generation Features

101

102

### JSON Write Features

103

104

```java { .api }

105

public enum JsonWriteFeature implements FormatFeature {

106

QUOTE_FIELD_NAMES(true),

107

WRITE_NAN_AS_STRINGS(false),

108

WRITE_NUMBERS_AS_STRINGS(false),

109

ESCAPE_NON_ASCII(false),

110

WRITE_BIGDECIMAL_AS_PLAIN(false);

111

112

public boolean enabledByDefault();

113

public boolean enabledIn(int flags);

114

public int getMask();

115

}

116

```

117

118

### Stream Write Features

119

120

```java { .api }

121

public enum StreamWriteFeature implements JacksonFeature {

122

AUTO_CLOSE_TARGET(true),

123

AUTO_CLOSE_JSON_CONTENT(true),

124

FLUSH_PASSED_TO_STREAM(true),

125

WRITE_BIGDECIMAL_AS_PLAIN(false),

126

STRICT_DUPLICATE_DETECTION(false),

127

IGNORE_UNKNOWN(false);

128

129

public boolean enabledByDefault();

130

public boolean enabledIn(int flags);

131

public int getMask();

132

}

133

```

134

135

## Pretty Printing

136

137

### PrettyPrinter Interface

138

139

```java { .api }

140

public interface PrettyPrinter {

141

void writeRootValueSeparator(JsonGenerator gen) throws IOException;

142

void writeStartObject(JsonGenerator gen) throws IOException;

143

void writeEndObject(JsonGenerator gen, int nrOfEntries) throws IOException;

144

void writeObjectEntryValueSeparator(JsonGenerator gen) throws IOException;

145

void writeObjectFieldValueSeparator(JsonGenerator gen) throws IOException;

146

void writeStartArray(JsonGenerator gen) throws IOException;

147

void writeEndArray(JsonGenerator gen, int nrOfValues) throws IOException;

148

void writeArrayValueSeparator(JsonGenerator gen) throws IOException;

149

void beforeArrayValues(JsonGenerator gen) throws IOException;

150

void beforeObjectEntries(JsonGenerator gen) throws IOException;

151

}

152

```

153

154

### Default Pretty Printer

155

156

```java { .api }

157

public class DefaultPrettyPrinter implements PrettyPrinter, Instantiatable<DefaultPrettyPrinter>, Serializable {

158

public DefaultPrettyPrinter();

159

public DefaultPrettyPrinter(String rootSeparator);

160

public DefaultPrettyPrinter(DefaultPrettyPrinter base);

161

162

public DefaultPrettyPrinter withRootSeparator(String sep);

163

public DefaultPrettyPrinter withObjectIndenter(Indenter oi);

164

public DefaultPrettyPrinter withArrayIndenter(Indenter ai);

165

public DefaultPrettyPrinter withSeparators(Separators separators);

166

}

167

168

public interface Indenter {

169

void writeIndentation(JsonGenerator gen, int level) throws IOException;

170

boolean isInline();

171

}

172

173

public class DefaultIndenter implements Indenter, Serializable {

174

public static final DefaultIndenter SYSTEM_LINEFEED_INSTANCE;

175

public static final DefaultIndenter LF_INSTANCE;

176

177

public DefaultIndenter();

178

public DefaultIndenter(String indent, String eol);

179

}

180

```

181

182

### Setting Pretty Printer

183

184

```java { .api }

185

public JsonGenerator setPrettyPrinter(PrettyPrinter pp);

186

public PrettyPrinter getPrettyPrinter();

187

public JsonGenerator useDefaultPrettyPrinter();

188

```

189

190

## Configuration and Status

191

192

```java { .api }

193

public abstract boolean isClosed();

194

public JsonGenerator enable(StreamWriteFeature f);

195

public JsonGenerator disable(StreamWriteFeature f);

196

public boolean isEnabled(StreamWriteFeature f);

197

public int getFeatureMask();

198

public JsonGenerator setFeatureMask(int mask);

199

200

public JsonGenerator setCharacterEscapes(CharacterEscapes esc);

201

public CharacterEscapes getCharacterEscapes();

202

public JsonGenerator setHighestNonEscapedChar(int charCode);

203

public int getHighestEscapedChar();

204

```

205

206

## Context and Validation

207

208

```java { .api }

209

public JsonStreamContext getOutputContext();

210

public int getCurrentDepth();

211

public boolean canWriteStartObject();

212

public boolean canWriteStartArray();

213

public boolean canWriteFieldName();

214

public boolean canWriteValue();

215

```

216

217

## Usage Examples

218

219

### Basic JSON Generation

220

221

```java

222

StringWriter sw = new StringWriter();

223

JsonGenerator gen = factory.createGenerator(sw);

224

225

gen.writeStartObject();

226

gen.writeStringField("name", "John Doe");

227

gen.writeNumberField("age", 30);

228

gen.writeBooleanField("active", true);

229

gen.writeFieldName("address");

230

gen.writeStartObject();

231

gen.writeStringField("street", "123 Main St");

232

gen.writeStringField("city", "Anytown");

233

gen.writeEndObject();

234

gen.writeEndObject();

235

gen.close();

236

237

String json = sw.toString();

238

// Result: {"name":"John Doe","age":30,"active":true,"address":{"street":"123 Main St","city":"Anytown"}}

239

```

240

241

### Array Generation

242

243

```java

244

JsonGenerator gen = factory.createGenerator(outputStream);

245

246

gen.writeStartArray();

247

for (String item : items) {

248

gen.writeString(item);

249

}

250

gen.writeEndArray();

251

gen.close();

252

```

253

254

### With Pretty Printing

255

256

```java

257

JsonGenerator gen = factory.createGenerator(outputStream)

258

.useDefaultPrettyPrinter();

259

260

gen.writeStartObject();

261

gen.writeStringField("message", "Hello World");

262

gen.writeNumberField("timestamp", System.currentTimeMillis());

263

gen.writeEndObject();

264

gen.close();

265

266

// Result (formatted):

267

// {

268

// "message" : "Hello World",

269

// "timestamp" : 1638360000000

270

// }

271

```

272

273

### Custom Pretty Printer

274

275

```java

276

DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter()

277

.withObjectIndenter(new DefaultIndenter(" ", "\n"))

278

.withArrayIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);

279

280

JsonGenerator gen = factory.createGenerator(outputStream)

281

.setPrettyPrinter(prettyPrinter);

282

```

283

284

### Binary Data

285

286

```java

287

byte[] imageData = loadImageBytes();

288

JsonGenerator gen = factory.createGenerator(outputStream);

289

290

gen.writeStartObject();

291

gen.writeStringField("filename", "image.jpg");

292

gen.writeBinaryField("data", imageData); // Base64 encoded automatically

293

gen.writeEndObject();

294

gen.close();

295

```

296

297

### Streaming Large Arrays

298

299

```java

300

JsonGenerator gen = factory.createGenerator(outputStream);

301

302

gen.writeStartObject();

303

gen.writeStringField("status", "ok");

304

gen.writeArrayFieldStart("results");

305

306

// Stream large number of items without loading all into memory

307

for (ResultItem item : resultStream) {

308

gen.writeStartObject();

309

gen.writeStringField("id", item.getId());

310

gen.writeStringField("value", item.getValue());

311

gen.writeEndObject();

312

313

// Optional: flush periodically for large datasets

314

if (item.getIndex() % 1000 == 0) {

315

gen.flush();

316

}

317

}

318

319

gen.writeEndArray();

320

gen.writeEndObject();

321

gen.close();

322

```

323

324

### Error Handling

325

326

```java

327

try (JsonGenerator gen = factory.createGenerator(outputStream)) {

328

gen.writeStartObject();

329

gen.writeStringField("data", someValue);

330

gen.writeEndObject();

331

} catch (JsonGenerationException e) {

332

System.err.println("Generation error: " + e.getMessage());

333

} catch (IOException e) {

334

System.err.println("IO error: " + e.getMessage());

335

}

336

```

337

338

### Character Escaping

339

340

```java { .api }

341

public abstract class CharacterEscapes {

342

public static final int ESCAPE_NONE = 0;

343

public static final int ESCAPE_STANDARD = -1;

344

public static final int ESCAPE_CUSTOM = -2;

345

346

public abstract int[] getEscapeCodesForAscii();

347

public abstract SerializableString getEscapeSequence(int ch);

348

}

349

```

350

351

Example with custom escaping:

352

```java

353

CharacterEscapes customEscapes = new CharacterEscapes() {

354

@Override

355

public int[] getEscapeCodesForAscii() {

356

int[] escapes = CharacterEscapes.standardAsciiEscapesForJSON();

357

escapes['<'] = CharacterEscapes.ESCAPE_CUSTOM;

358

escapes['>'] = CharacterEscapes.ESCAPE_CUSTOM;

359

return escapes;

360

}

361

362

@Override

363

public SerializableString getEscapeSequence(int ch) {

364

switch (ch) {

365

case '<': return new SerializedString("&lt;");

366

case '>': return new SerializedString("&gt;");

367

default: return null;

368

}

369

}

370

};

371

372

JsonGenerator gen = factory.createGenerator(outputStream)

373

.setCharacterEscapes(customEscapes);

374

```