Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

json-io

> 编程语言
Open source

Convert Java to JSON/TOON and back. Supports complex object graphs, cyclic references, and TOON format for 40-50% LLM token savings

389 stars0 likes0 views
WebsiteGitHub

About

Convert Java to JSON/TOON and back. Supports complex object graphs, cyclic references, and TOON format for 40-50% LLM token savings

Infographic by Guillaume Laforge

LLM applications waste 40-50% of their token budget on JSON syntax overhead — braces, brackets, quotes, and commas that carry zero semantic information. json-io is a Java serialization library that reads and writes JSON, JSON5, and TOON (Token-Oriented Object Notation) — a format that strips that overhead while preserving full data fidelity. It also handles what Jackson/Gson cannot: cyclic object graphs, automatic polymorphic types, and zero-config serialization of 60+ built-in Java types.

Featured on json.org and Baeldung. See the interactive JSON vs TOON comparison.

Quick Start

java
// JSON
String json = JsonIo.toJson(myObject);
MyClass obj = JsonIo.toJava(json).asClass(MyClass.class);

// JSON5
String json5 = JsonIo.toJson(myObject, new WriteOptionsBuilder().json5().build());

// TOON (~40-50% fewer tokens than JSON)
String toon = JsonIo.toToon(myObject);
MyClass obj = JsonIo.fromToon(toon).asClass(MyClass.class);

// Standard JSON (Jackson-compatible output — no @type, no @id/@ref, stringified map keys)
String json = JsonIo.toJson(myObject, new WriteOptionsBuilder().standardJson().build());

Installation

Gradle

groovy
implementation 'com.cedarsoftware:json-io:4.110.0'

Maven

xml

  com.cedarsoftware
  json-io
  4.110.0

Latest version:


JSON

Usage

java
// Write JSON
String json = JsonIo.toJson(myObject);
JsonIo.toJson(outputStream, myObject, writeOptions);

// Read JSON to typed Java objects
Employee emp = JsonIo.toJava(json).asClass(Employee.class);
Employee emp = JsonIo.toJava(inputStream, readOptions).asClass(Employee.class);

// Read JSON to Maps (no classes needed)
Map map = JsonIo.toMaps(json).asMap();

// Generic types
List list = JsonIo.toJava(json).asType(new TypeHolder>(){});

Standard JSON Mode — Jackson Compatible

One flag flips json-io's output to match Jackson. Use standardJson() to produce output byte-compatible with what Jackson (with JavaTimeModule and the Spring Boot default of WRITE_DATES_AS_TIMESTAMPS=false) produces:

java
WriteOptions opts = new WriteOptionsBuilder()
        .standardJson()    // will be the default in 5.0.0 — this call becomes optional
        .build();
String json = JsonIo.toJson(myObject, opts);

This configures: showTypeInfoNever, showRootTypeInfo(false), cycleSupport(false), stringifyMapKeys(true), writeOptionalAsObject(false), preserveLeafContainerIdentity(false), isoDateFormat() (ISO-8601 dates for java.util.Date — java.time.* are already ISO-8601), and useMetaPrefixDollar().

Use json-io anywhere you'd use Jackson for standard JSON output, and get the full json-io feature set whenever you need it: cyclic graph preservation, polymorphic @type auto-detection, and first-class JSON5 + TOON output — all from the same builder.

Need Jackson-style output plus graph fidelity? If your data has shared references or cycles and you want them preserved (something Jackson only does with @JsonIdentityInfo annotated on every affected class), turn cycle support back on after standardJson():

java
WriteOptions opts = new WriteOptionsBuilder()
        .standardJson()
        .cycleSupport(true)    // Jackson-compatible output, but $id/$ref are emitted when shared refs exist
        .build();

You get Jackson-compatible field names, ISO-8601 dates, and stringified Map keys — plus json-io's automatic shared-reference and cycle preservation. No class annotations required.

json-io vs Jackson vs Gson

Object graph handling

Capability json-io Jackson Gson
Cyclic object graphs Automatic ($id/$ref) -or- JsonIoException with cycleSupport(false) Requires @JsonIdentityInfo StackOverflowError
Shared object references Preserved ($id/$ref) -or- duplicated with cycleSupport(false) Requires @JsonIdentityInfo Duplicated (no identity)
Polymorphic types Automatic -or- use @IoTypeInfo/@JsonTypeInfo Requires @JsonTypeInfo Requires TypeAdapter
Unknown $type values Graceful fallback to Map Exception Exception

Map handling

Capability json-io Jackson Gson
Map Standard JSON object Same Same
Map, Map stringifyMapKeys → {"100": v} toString() (fragile) enableComplexMapKeySerialization()
Map (complex keys) Full fidelity via $keys/$items toString() (lossy) Array of key-value pairs

Format & configuration

Capability json-io Jackson Gson
Standard JSON output .standardJson() — Jackson-compatible Default Default
JSON5 support Full read/write (native) Partial read only None
TOON support Full read/write (40-50% fewer tokens) None None
Configuration Zero-config; optional @Io* Annotation-heavy (@Json*) Annotations + builders
Jackson annotations Recognized reflectively (v2 & v3) Native Not supported
Two parse modes toJava() (typed) + toMaps() Typed only Typed only

Runtime

Capability json-io Jackson Gson
Performance (simple DTOs) 1.3–1.8x vs Jackson (all paths under 2x) Fastest 1.4–2.1x vs Jackson
Dependencies java-util only (~850K) Multiple JARs (~2.5MB+) Single JAR (~300KB)
Java version JDK 1.8+ JDK 1.8+ JDK 1.8+

On performance: Jackson is faster for simple DTOs, but json-io stays under 2x Jackson on every read/write mode on the JsonPerformanceTest benchmark (100,000 iterations, diverse POJO workload — nested collections, floats, BigDecimal, java.time.*, UUIDs, nullable fields). json-io beats Gson on every write mode and is roughly tied with Gson on reads. In real-world applications, serialization is typically writes{"100": value}withstringifyMapKeys(true)`

  • Extensive configuration via ReadOptionsBuilder and WriteOptionsBuilder
  • Parse JSON with unknown $type references into a Map-of-Maps without requiring classes on classpath

JSON5

JSON5 is an extension to JSON that makes it more human-friendly. json-io provides complete JSON5 support for both reading and writing — the only major Java JSON library to do so natively.

Reading JSON5

json-io accepts all JSON5 extensions by default — no configuration needed:

java
String json5 = "{ name: 'John', age: 30, /* comment */ }";
Person p = JsonIo.toJava(json5).asClass(Person.class);

Supported: single-line (//) and multi-line (/* */) comments, single-quoted strings, unquoted keys, trailing commas, hex integers, Infinity/NaN/-Infinity, and more.

Writing JSON5

java
WriteOptions opts = new WriteOptionsBuilder().json5().build();
String json5 = JsonIo.toJson(myObject, opts);

The json5() umbrella enables:

  • Unquoted keys — object keys that are valid identifiers are written without quotes
  • Smart quotes — strings containing " (but not ') use single quotes
  • Infinity/NaN literals — special float/double values as literals instead of null
  • Stringify map keys — Map writes {100: value} instead of $keys/$items
  • No type info — showTypeInfoNever() + cycleSupport(false) for clean output

Individual features can be enabled separately. See the User Guide for details.

TOON

TOON (Token-Oriented Object Notation) is an indentation-based format that produces ~40-50% fewer tokens than JSON — ideal for LLM applications where token count directly impacts cost and context window usage.

  • No braces, brackets, or commas — structure is expressed through indentation
  • No quoting for most keys and values — quotes only when needed
  • Compact arrays — inline [N]: a,b,c or list format with - prefixed elements
  • Tabular format — arrays of uniform objects as CSV-like rows with column headers
  • Key folding — nested keys like address.city: Denver flatten one level of nesting
  • Full fidelity — most data requires no extra metadata at all
  • TOON v3.3 spec-conformant — passes the full official upstream fixture suite (encode + decode + strict-mode validation)

JSON:

json
{"team":"Rockets","players":[{"name":"John","age":30,"position":"guard"},{"name":"Sue","age":27,"position":"forward"},{"name":"Mike","age":32,"position":"center"}]}

TOON (same data, ~45% fewer tokens):

yaml
team: Rockets
players:
  name, age, position
  John, 30, guard
  Sue, 27, forward
  Mike, 32, center

Usage

java
// Write TOON
String toon = JsonIo.toToon(myObject);

// Read TOON back to typed Java object
Person p = JsonIo.fromToon(toon).asClass(Person.class);

// Read TOON to Maps (no class needed)
Map map = JsonIo.fromToon(toon).asMap();

Request TOON format for LLM applications: Accept: application/vnd.toon

See the Baeldung tutorial for a walkthrough of JSON, JSON5, and TOON serialization with json-io, and the interactive JSON vs TOON comparison.

vs JToon

Capability json-io JToon
Built-in types 60+ ~15
Map key types Any serializable type Strings only
EnumSet support Yes No
Full Java serialization Yes — any object graph Limited to supported types
Cycle support ($id/$ref) Yes (opt-in) No
Annotation support @Io* + Jackson (reflective) None
Dependencies java-util only Jackson
Status Stable, production-ready Beta (v1.x.x)

Spring Boot Integration

json-io provides a Spring Boot starter for seamless integration with Spring MVC and WebFlux applications.

Standalone or with Spring — your choice. json-io's core has no Spring dependency (its only runtime dependency is java-util), so it works anywhere. The Spring Boot starter is an optional, non-intrusive add-on: it declares Spring as provided, so it plugs into your application's own Spring and forces no Spring version onto your build — your Boot version always wins, and adding the starter puts nothing on your classpath but json-io itself. Works on Spring Boot 3.x and 4.x — the shipped starter uses only Spring Framework-level APIs (no Boot-version-specific types), so one artifact runs on both majors: compiled against a Spring Boot 3.4 (Spring 6.2) floor, forward-tested across Boot 3.x, and runtime-verified on Spring Boot 4.1 / Spring 7 (auto-configuration, HTTP message converters, and reactive codecs).

xml

  com.cedarsoftware
  json-io-spring-boot-starter
  4.110.0

Your REST controllers now support JSON, JSON5, and TOON formats via content negotiation:

java
@RestController
public class ApiController {
    @GetMapping("/data")
    public MyData getData() {
        return myData;  // Returns JSON, JSON5, or TOON based on Accept header
    }
}

Spring AI Integration

json-io provides a Spring AI module that reduces LLM token usage by ~40-50% using TOON format for tool call results and structured output parsing.

xml

  com.cedarsoftware
  json-io-spring-ai-toon
  4.110.0

Auto-configured: tool call results are serialized to TOON automatically. For structured output, use ToonBeanOutputConverter:

java
ToonBeanOutputConverter converter = new ToonBeanOutputConverter<>(Person.class);
Person person = chatClient.prompt()
    .user("Get info about John")
    .call()
    .entity(converter);

Also supports WebFlux and WebClient for reactive applications.

See the [Spring Integration Guide](/u

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Java

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言