Java guide
Every Java entry point, what it writes, and when to use it. Everything on this page writes the same 2.x documents as the Python and TypeScript SDKs, so a Java service and a Python agent read each other's data exactly.
Pick an entry point
| You have | Use | Module |
|---|---|---|
| Maps, lists and records; the fastest path | DocCodec | jdogo-core |
| Your own classes, with limits from configuration | JDogoMapper | jdogo-core + jdogo-compact |
| Data for a model prompt, or a question to answer exactly | JDogoAI | jdogo-optimizer |
| A Spring Boot web app | The starter | jdogo-spring-boot-starter |
Jackson JsonNode trees | JDogoTreeCodec | jdogo-jackson |
| Kotlin | Reified extensions | jdogo-kotlin |
| Tables too large for memory | Streaming reader and writer | jdogo-core |
All modules use the group com.jdogo and version 2.1.0, and need Java 17 or newer. See Install.
The document codec
Static methods, no setup. Records are written by component name, in declaration order.
import com.jdogo.core.doc.DocCodec;
record Order(int id, String sku, String status, double total) {}
String text = DocCodec.encodeRecords(orders); // List<Order> to a table
List<Order> back = DocCodec.decodeRecords(text, Order.class);
String doc = DocCodec.encode(Map.of("region", "EU", "rows", rows)); // any map, list or scalar
Object tree = DocCodec.decode(doc); // maps, lists, strings, numbers
byte[] bytes = DocCodec.encodeToBytes(rows); // UTF-8, for queues and files
Object again = DocCodec.decode(bytes);For a model prompt, DocCodec.encodeLegibleKeys(rows) writes the layout the recorded accuracy runs measured; JDogoAI.formatQueryPrompt adds the instruction. See AI prompts and ask().
Classes, enums and dates
DocBinder turns any object into the plain tree the codec writes, and binds a tree back to a type. The mapper and the Spring converter use it for you.
import com.jdogo.core.doc.DocBinder; Object tree = DocBinder.toTree(invoice); // records, beans, enums, UUID, java.time, Optional String text = DocCodec.encode(tree); Invoice back = DocBinder.fromTree(DocCodec.decode(text), Invoice.class);
| Java value | Written as |
|---|---|
| Record, bean (getters or fields) | An object with one key per property |
| Enum | Its name |
UUID, Instant, LocalDate, Duration and other java.time values | Their ISO toString() |
byte[] | URL-safe Base64 without padding |
Optional | Its value, or null |
When binding, unknown keys are ignored and missing keys leave the default. A value of the wrong kind fails with the path that broke, for example Cannot bind $[3].qty to int: found a string.
The object mapper
import com.jdogo.api.*;
import com.jdogo.api.type.TypeReference;
import com.jdogo.core.mapper.JDogoCoreMapper;
JDogoMapper mapper = JDogoCoreMapper.create(JDogoConfig.builder()
.maxDepth(32)
.maxPayloadBytes(5_000_000)
.allowPolymorphicPrefix("com.example.") // your packages; see below
.build());
String text = mapper.encode(orders);
List<Order> back = mapper.decode(text, new TypeReference<List<Order>>() {});
Order one = mapper.decode(mapper.encode(order), Order.class);
mapper.write(orders, outputStream); // streams too| Setting | Default | Effect |
|---|---|---|
formatMode | COMPACT | COMPACT writes the 2.x document; TYPED keeps exact Java types (for example BigDecimal scale) in a schema header for Java-to-Java use; JSON writes JSON; ADAPTIVE detects the input format when reading |
maxDepth | 64 | Deepest nesting accepted, writing and reading |
maxCollectionSize | 100,000 | Most items in one list or map when reading |
maxPayloadBytes | 50 MB | Largest input accepted when reading |
referenceTracking | false | Keeps shared and cyclic objects. Uses the 1.x object form, which only the Java mapper reads back |
allowPolymorphicPrefix | java., com.jdogo. | Packages a top-level target class may come from |
The package allowlist. decode(text, Order.class) refuses classes outside the allowed packages, and the error names the call that allows yours. Payloads never name classes, so this guards which types your own code binds to. Element types inside a TypeReference are not checked.
Reading 1.x text. The mapper still reads the 1.x pipe format (1|Ana|Paris), so stored data keeps working. It writes 2.x.
Spring Boot
<dependency> <groupId>com.jdogo</groupId> <artifactId>jdogo-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
A standard Spring Boot 3 auto-configuration. Your controllers don't change:
@GetMapping("/orders")
List<Order> orders() { return repository.findAll(); }curl -H 'Accept: application/jdogo' localhost:8080/orders # JDogo curl localhost:8080/orders # JSON, as before
- A
JDogoMapperbean from thejdogo.*settings. Declare your own bean to replace it. - In a Spring MVC app, a message converter added after Jackson. Clients that ask for
application/jdogoget JDogo; everyone else keeps JSON. Request bodies sent asapplication/jdogoare read too. - Objects are bound with your application's Jackson
ObjectMapper, so@JsonProperty,@JsonIgnore, date settings and modules work as they do for JSON. - Media types:
application/jdogo(what the Python and TypeScript middleware send),application/jdogo+compact,application/jdogo+typedandapplication/x-jdogo.
| Property | Default |
|---|---|
jdogo.http.enabled | true. Set false to keep the mapper bean without the converter |
jdogo.max-depth | 64 |
jdogo.max-collection-size | 100000 |
jdogo.max-payload-bytes | 52428800 (50 MB) |
jdogo.format-mode | compact |
jdogo.reference-tracking, jdogo.strict-type-validation, jdogo.pretty-print | Mapper settings, as above |
Compiled against Spring Boot 3.3; works with Spring Boot 3.x on Spring Framework 6. WebFlux is not covered yet.
Spring AI and other agent frameworks
Plain helpers with no framework dependency: they return strings you put in a prompt or return from a tool.
import com.jdogo.spring.ai.SpringAiPromptOptimizer; import com.jdogo.spring.ai.JDogoToolCallCompactor; var prompts = new SpringAiPromptOptimizer(); String context = prompts.optimizeContextForPrompt(transactions); // with a one-line format note String reply = chatClient.prompt().system(context).user(question).call().content(); var tools = new JDogoToolCallCompactor(); String result = tools.compactToolResponse(rows); // return from a @Tool method Object args = tools.decompactToolArguments(argumentText);
Jackson
import com.jdogo.jackson.JDogoTreeCodec; ObjectMapper mapper = new ObjectMapper(); var codec = new JDogoTreeCodec(mapper); String text = codec.toJDogo(mapper.readTree(json)); JsonNode node = codec.fromJDogo(text); // also reads typed documents and plain JSON
Kotlin
import com.jdogo.kotlin.decode import com.jdogo.kotlin.decodeList @JvmRecord data class User(val id: Long, val name: String) val user: User = mapper.decode(text) val users: List<User> = mapper.decodeList(text) val streamed: User = mapper.read(inputStream)
Token optimizer and cost
Pick the cheapest format for a payload, or estimate what a switch saves per month.
import com.jdogo.ai.CostEstimator;
import com.jdogo.ai.optimizer.JDogoOptimizer;
OptimizedPayload p = JDogoOptimizer.builder()
.strategy(OptimizationStrategy.MINIMUM_TOKENS)
.build()
.optimize(rows);
p.content(); // the text to send
p.tokenReductionPercent(); // against JSON, measured with the tokenizer
var est = CostEstimator.estimate(rows, "my-model",
CostEstimator.Pricing.of(3.00, 15.00), // $ per million input, output tokens
new CostEstimator.Traffic(1_000_000, "How many are late?", 200, 0.0));
System.out.println(est.summary());Use the prices you actually pay. The model presets inside JDogoContextProfiler are dated examples.
JDogoChatCompressor.compress(messages)rewrites JSON inside chat messages as JDogo and reports the tokens saved.JDogoGbnfGenerator.generateTableGrammar(columns)andgenerateSchemaGrammar(Order.class)build GBNF grammars for llama.cpp, Ollama and vLLM.AccuracyRiskEstimator.assess(rowCount, payload, modelId)is a rule of thumb for when to send rows and when to send a schema card and useask(). It is a heuristic, not a measurement.
More Java modules
- Context sync: versioned snapshots, deltas, signed envelopes, server-sent events and Redis or SQL stores.
- Schemas and Arrow: a schema registry with compatibility checks, and column batches.
- MCP server: the
jdogo-clijar runs one for any MCP client.