TOON format reduces token usage by approximately 50% compared to JSON when working with OpenAI, Claude, or other LLM APIs. This guide shows you how to implement TOON in Java applications.
Whether you're building with Spring Boot, Jakarta EE, or just using the OpenAI Java SDK, this guide has you covered. We'll go from zero to a working implementation with real code examples you can use right away.
Contents:
- Installing and setting up TOON in your Java project (Maven/Gradle)
- Parsing and generating TOON data
- Converting between JSON and TOON
- Integrating with OpenAI, Anthropic Claude, and other LLM APIs
- Working with POJOs and collections
- Real-world examples and best practices
Prerequisites
Before we start, make sure you have:
Development Environment
- Java 11 or higher
- Maven or Gradle
- Your favorite IDE (IntelliJ, Eclipse, VS Code)
Knowledge
- Basic Java programming
- Understanding of JSON and Maps
- (Optional) OpenAI API basics
Step 1: Installation
Let's install the TOON library for Java. Choose your build tool below:
Using Maven (Recommended)
Add this dependency to your pom.xml:
<dependency>
<groupId>io.toon</groupId>
<artifactId>toon-java</artifactId>
<version>1.0.0</version>
</dependency>Using Gradle
Add this to your build.gradle:
implementation 'io.toon:toon-java:1.0.0'
Sync Your Project
After adding the dependency, sync your project in your IDE to download the library.
Pro Tip
The package includes everything you need: parser, serializer, JSON converter, token counter, and LLM integration helpers!
Step 2: Your First TOON Program 🚀
Let's start with a simple "Hello World" example. Here's how to parse and generate TOON data:
📝Example: Parsing TOON Data
import io.toon.Toon;
import io.toon.ToonObject;
public class ToonExample {
public static void main(String[] args) {
String toonData = """
name: "John Smith"
age: 32
email: "[email protected]"
active: true
""";
ToonObject obj = Toon.parse(toonData);
String name = obj.getString("name");
int age = obj.getInt("age");
String email = obj.getString("email");
boolean active = obj.getBoolean("active");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}Output:
Name: John Smith Age: 32
📊Example: Parsing Arrays
String toonData = """
users[3]{id,name,email}:
1,Alice,[email protected]
2,Bob,[email protected]
3,Carol,[email protected]
""";
ToonObject obj = Toon.parse(toonData);
ToonArray users = obj.getArray("users");
for (ToonObject user : users) {
int id = user.getInt("id");
String name = user.getString("name");
String email = user.getString("email");
System.out.println(id + ": " + name + " - " + email);
}Output:
1: Alice - [email protected] 2: Bob - [email protected] 3: Carol - [email protected]
Tip: Use Java's text blocks (""") for multi-line TOON strings. They're perfect for TOON data.
Step 3: Converting Java Objects to TOON 🔄
You can convert Java objects to TOON format for use in LLM prompts or API calls:
Using POJOs:
public class User {
private int id;
private String name;
private String email;
private boolean active;
// Constructor, getters, and setters
}
// Create a user
User user = new User();
user.setId(1);
user.setName("Alice Johnson");
user.setEmail("[email protected]");
user.setActive(true);
// Convert to TOON
String toonString = Toon.stringify(user);
System.out.println(toonString);
// Output:
// id: 1
// name: "Alice Johnson"
// email: "[email protected]"
// active: trueConverting Lists:
List<User> users = Arrays.asList(
new User(1, "Alice", "[email protected]", true),
new User(2, "Bob", "[email protected]", true),
new User(3, "Carol", "[email protected]", false)
);
String toonString = Toon.stringify(users);
System.out.println(toonString);
// Output:
// users[3]{id,name,email,active}:
// 1,Alice,[email protected],true
// 2,Bob,[email protected],true
// 3,Carol,[email protected],false💰 Typical Savings: 48-52% fewer tokens!
That means your OpenAI API costs are cut in half.
Step 4: OpenAI API Integration 🤖
Here's where TOON really pays off! Let's integrate it with the OpenAI API to save tokens and money:
💸Save Money on Every API Call!
By using TOON instead of JSON in your prompts, you'll cut token usage by ~50%, which means your API costs are cut in half too!
Complete OpenAI Example:
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
public class ToonLLMExample {
public static void main(String[] args) {
// Your data in TOON format (50% fewer tokens than JSON)
String customerData = """
customers[3]{id,name,plan,revenue}:
1,Acme Corp,Enterprise,50000
2,TechStart,Pro,5000
3,DataCo,Basic,500
""";
String prompt = "Analyze this customer data and identify upsell opportunities:\n\n"
+ customerData;
// OpenAI API call
OpenAiService service = new OpenAiService("your-api-key");
ChatCompletionRequest request = ChatCompletionRequest.builder()
.model("gpt-4")
.messages(Arrays.asList(
new ChatMessage("user", prompt)
))
.build();
String response = service.createChatCompletion(request)
.getChoices().get(0).getMessage().getContent();
System.out.println(response);
}
}💰 Token Savings
The TOON format in this example uses approximately 50% fewer tokens compared to equivalent JSON. For a dataset with 100 customers, this could save you $0.50-$5.00 per API call depending on the model.
Reading and Writing TOON Files
Working with TOON files is similar to working with JSON files:
Reading from File
import java.nio.file.Files;
import java.nio.file.Path;
public class ToonFileExample {
public static void main(String[] args) throws Exception {
// Read TOON file
String toonContent = Files.readString(Path.of("data.toon"));
ToonObject data = Toon.parse(toonContent);
// Access the data
String name = data.getString("name");
ToonArray items = data.getArray("items");
System.out.println("Loaded " + items.size() + " items");
}
}Writing to File
public static void saveToonFile(Object data, String filename) throws Exception {
String toonString = Toon.stringify(data);
Files.writeString(Path.of(filename), toonString);
}
// Usage
List<Product> products = getProducts();
saveToonFile(products, "products.toon");Error Handling 🛡️
Always handle errors gracefully. Here's a production-ready example:
import io.toon.ToonException;
public void safeParseToon(String toonData) {
try {
ToonObject obj = Toon.parse(toonData);
// Process data
} catch (ToonException e) {
System.err.println("TOON parsing error: " + e.getMessage());
System.err.println("Line: " + e.getLine());
System.err.println("Column: " + e.getColumn());
// Handle error appropriately
}
}Validation Tip: Use the TOON Validator during development to catch syntax errors before they reach your Java code.
Best Practices & Tips 💡
- 1Use Text Blocks for TOON Literals
Java's text blocks (
""") are perfect for embedding TOON data in your code. - 2Cache Parsed Objects
If you're parsing the same TOON data repeatedly, cache the parsed ToonObject to improve performance.
- 3Use DTOs with Annotations
Annotate your Java classes with
@ToonPropertyfor custom field mappings. - 4Validate TOON Before Parsing
Use
Toon.isValid()to check if a string is valid TOON before attempting to parse it. - 5Monitor Token Usage
Use
Toon.estimateTokens()to estimate token count before sending data to LLM APIs.
Complete Working Example
Here's a complete example that puts everything together:
import io.toon.*;
import java.util.*;
public class CustomerAnalyzer {
public static class Customer {
private int id;
private String name;
private String tier;
private double revenue;
// Constructor, getters, setters omitted for brevity
}
public static void main(String[] args) {
// Load customer data
List<Customer> customers = Arrays.asList(
new Customer(1, "Acme Corp", "Enterprise", 50000),
new Customer(2, "TechStart", "Pro", 5000),
new Customer(3, "DataCo", "Basic", 500)
);
// Convert to TOON (50% fewer tokens than JSON)
String toonData = Toon.stringify(customers);
System.out.println("TOON Format:");
System.out.println(toonData);
// Estimate tokens
int tokenCount = Toon.estimateTokens(toonData);
System.out.println("\nEstimated tokens: " + tokenCount);
// Send to LLM API
String analysis = analyzWithLLM(toonData);
System.out.println("\nAnalysis: " + analysis);
}
private static String analyzWithLLM(String toonData) {
String prompt = "Analyze these customers:\n" + toonData;
// Your LLM API call here
return "Analysis results...";
}
}Common Issues and Solutions
Issue: ClassNotFoundException
Make sure the TOON library is properly added to your classpath. Check your Maven/Gradle configuration.
Issue: ToonException on Valid Data
Check for whitespace issues. TOON uses 2-space indentation, not tabs. Use a TOON validator to verify your format.
Issue: Null Values Not Handled
Use obj.isNull("field") to check before accessing values, or use getStringOrNull() methods.
Helpful Tools 🛠️
These free online tools will help you work with TOON:
Related Articles
TOON Format Guides
- What is TOON Format?
Introduction to TOON format
- TOON vs JSON
Compare TOON and JSON formats
- TOON Specification
Technical specification
Other Languages
- TOON in Python
Python integration guide
- TOON in C#
C# integration guide
- TOON for LLM Prompts
LLM best practices
Additional Resources
- •TOON Java Library on GitHub
Official Java implementation with examples
- •OpenAI API Documentation
Official OpenAI API reference for Java integration
- •Maven Getting Started Guide
Learn Maven dependency management
- •Java Generics Tutorial
Official Oracle Java generics documentation
- •OpenAI Tokenizer Tool
Test and compare TOON vs JSON token counts
- •JSON Specification
Official JSON format specification
- •TOON vs JSON Comparison
Detailed performance comparison
- •TOON Format Specification
Complete syntax and structure guide