JDogo
Open playground

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 haveUseModule
Maps, lists and records; the fastest pathDocCodecjdogo-core
Your own classes, with limits from configurationJDogoMapperjdogo-core + jdogo-compact
Data for a model prompt, or a question to answer exactlyJDogoAIjdogo-optimizer
A Spring Boot web appThe starterjdogo-spring-boot-starter
Jackson JsonNode treesJDogoTreeCodecjdogo-jackson
KotlinReified extensionsjdogo-kotlin
Tables too large for memoryStreaming reader and writerjdogo-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 valueWritten as
Record, bean (getters or fields)An object with one key per property
EnumIts name
UUID, Instant, LocalDate, Duration and other java.time valuesTheir ISO toString()
byte[]URL-safe Base64 without padding
OptionalIts 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
SettingDefaultEffect
formatModeCOMPACTCOMPACT 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
maxDepth64Deepest nesting accepted, writing and reading
maxCollectionSize100,000Most items in one list or map when reading
maxPayloadBytes50 MBLargest input accepted when reading
referenceTrackingfalseKeeps shared and cyclic objects. Uses the 1.x object form, which only the Java mapper reads back
allowPolymorphicPrefixjava., 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
PropertyDefault
jdogo.http.enabledtrue. Set false to keep the mapper bean without the converter
jdogo.max-depth64
jdogo.max-collection-size100000
jdogo.max-payload-bytes52428800 (50 MB)
jdogo.format-modecompact
jdogo.reference-tracking, jdogo.strict-type-validation, jdogo.pretty-printMapper 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.

More Java modules