Camel data formats: turning bytes into objects and back
Messages travel as bytes: JSON from an API, XML from a partner, CSV from a file drop. Inside a route you usually want Java objects instead. Camel's data formats do that conversion in one step, marshal and unmarshal. This page explains how data formats fit into a route, then runs JSON, XML, CSV, Bindy and a custom format with Camel 4.23, including the errors each one gives when the data does not match.
Contents
What a data format does
Endpoints move bytes. An HTTP call returns a JSON document, a file consumer delivers a CSV file, a JMS queue carries XML. Business logic, on the other hand, wants an Order
- unmarshal: wire format to Java.
reads the body as bytes or text and replaces it with an object.unmarshal(json) - marshal: Java to wire format.
takes the object in the body and replaces it with the encoded bytes.marshal(json)
Each data format implements one interface, org.apache.camel.spi.DataFormatmarshal(Exchange, Object, OutputStream)unmarshal(Exchange, InputStream)Service
| Format | Module | Library | Best for |
|---|---|---|---|
| JSON | camel-jackson | Jackson 2 (2.21 here) | REST APIs and events |
| JSON | camel-jackson3 (since Camel 4.19) | Jackson 3 | Applications that have moved to Jackson 3 |
| XML | camel-jaxb | Jakarta XML Binding 4 | XML with a schema or annotated classes |
| CSV | camel-csv | Apache Commons CSV | Rows as lists or maps, without classes |
| CSV, fixed length, key-value | camel-bindy | Annotations on your classes | Typed records from flat files |
| Your own | Your code | DataFormat | Formats with no Camel module |
A data format differs from a type converter: a type converter turns one Java type into another, such as StringInteger
JSON with Jackson
JSON is the most common case. This program turns a JSON document into a Java record and back, reads an array as a list, and shows what happens when no target type is given:
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
public class JsonJackson {
public record Order(String id, String item, int quantity) {
}
static class Routes extends RouteBuilder {
@Override
public void configure() {
JacksonDataFormat orderJson = new JacksonDataFormat(Order.class);
JacksonDataFormat orderListJson = new JacksonDataFormat(Order.class);
orderListJson.setUseList(true);
from("direct:toObject")
.unmarshal(orderJson)
.process(e -> System.out.println(" body type: "
+ e.getMessage().getBody().getClass().getSimpleName()));
from("direct:toJson")
.marshal(orderJson)
.process(e -> System.out.println(" body type: "
+ e.getMessage().getBody().getClass().getSimpleName()))
.convertBodyTo(String.class);
from("direct:toList")
.unmarshal(orderListJson);
from("direct:untyped")
.unmarshal().json();
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
String json = "{\"id\":\"A-1\",\"item\":\"book\",\"quantity\":2}";
System.out.println("unmarshal JSON to a record:");
Order order = template.requestBody("direct:toObject", json, Order.class);
System.out.println(" " + order);
System.out.println("marshal the record back to JSON:");
System.out.println(" " + template.requestBody("direct:toJson", order, String.class));
String array = "[{\"id\":\"A-1\",\"item\":\"book\",\"quantity\":2},"
+ "{\"id\":\"A-2\",\"item\":\"lamp\",\"quantity\":1}]";
List<?> orders = template.requestBody("direct:toList", array, List.class);
System.out.println("useList: " + orders.size() + " orders, first is "
+ orders.get(0).getClass().getSimpleName());
Object untyped = template.requestBody("direct:untyped", json);
System.out.println("no type: " + untyped.getClass().getSimpleName() + " " + untyped);
camel.stop();
}
}
unmarshal JSON to a record:
body type: Order
Order[id=A-1, item=book, quantity=2]
marshal the record back to JSON:
body type: InputStreamCache
{"id":"A-1","item":"book","quantity":2}
useList: 2 orders, first is Order
no type: LinkedHashMap {id=A-1, item=book, quantity=2}
withunmarshal produced annew JacksonDataFormat(Order.class) record. Jackson 2.12 and later bind records through their canonical constructor, so no setters or annotations are needed.Order produced the JSON text again. Right after marshalling, the body was anmarshal , not aInputStreamCache : data formats write to a stream, and Camel's stream caching kept it re-readable.String made it text.convertBodyTo(String.class) read the JSON array as asetUseList(true) of twoList records. Without it, Jackson would try to read an array into a singleOrder and fail.Order without a type produced aunmarshal().json() . That is handy for quick routing on a field, but it gives up type checking, and numbers arrive as whatever Jackson picks, such asLinkedHashMap orInteger .Double
camel-jackson uses Jackson 2. Camel 4.19 added camel-jackson3 for Jackson 3, whose core packages moved from com.fasterxml.jacksontools.jackson
JSON traps: unknown fields and Java time
Two Jackson defaults break routes in production more than any others. Here a payment arrives with a field the class does not have, and a shipment with a LocalDate
import java.time.LocalDate;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
public class JsonTraps {
public record Payment(String id, double amount) {
}
public record Shipment(String id, LocalDate shipped) {
}
static class Routes extends RouteBuilder {
@Override
public void configure() {
errorHandler(defaultErrorHandler().logExhausted(false));
JacksonDataFormat strict = new JacksonDataFormat(Payment.class);
JacksonDataFormat lenient = new JacksonDataFormat(Payment.class);
lenient.setDisableFeatures("FAIL_ON_UNKNOWN_PROPERTIES");
from("direct:strict").unmarshal(strict);
from("direct:lenient").unmarshal(lenient);
JacksonDataFormat plainDates = new JacksonDataFormat(Shipment.class);
JacksonDataFormat javaTime = new JacksonDataFormat(Shipment.class);
javaTime.setModuleClassNames("com.fasterxml.jackson.datatype.jsr310.JavaTimeModule");
javaTime.setDisableFeatures("WRITE_DATES_AS_TIMESTAMPS");
from("direct:plainDates").marshal(plainDates).convertBodyTo(String.class);
from("direct:javaTime").marshal(javaTime).convertBodyTo(String.class);
}
}
static void show(ProducerTemplate template, String label, String uri, Object body) {
Exchange result = template.send(uri, e -> e.getMessage().setBody(body));
String outcome = result.isFailed()
? result.getException().getClass().getSimpleName() + ": "
+ result.getException().getMessage().lines().findFirst().orElse("")
: String.valueOf(result.getMessage().getBody());
System.out.println(label + "\n " + outcome);
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
String withExtra = "{\"id\":\"P-9\",\"amount\":12.5,\"currency\":\"EUR\"}";
show(template, "strict, JSON has an extra field:", "direct:strict", withExtra);
show(template, "FAIL_ON_UNKNOWN_PROPERTIES disabled:", "direct:lenient", withExtra);
Shipment shipment = new Shipment("S-3", LocalDate.of(2026, 11, 2));
show(template, "LocalDate without the Java time module:", "direct:plainDates", shipment);
show(template, "with JavaTimeModule and ISO dates:", "direct:javaTime", shipment);
camel.stop();
}
}
strict, JSON has an extra field:
UnrecognizedPropertyException: Unrecognized field "currency" (class JsonTraps$Payment), not marked as ignorable (2 known properties: "amount", "id")
FAIL_ON_UNKNOWN_PROPERTIES disabled:
Payment[id=P-9, amount=12.5]
LocalDate without the Java time module:
InvalidDefinitionException: Java 8 date/time type `java.time.LocalDate` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (or disable `MapperFeature.REQUIRE_HANDLERS_FOR_JAVA8_TIMES`) (through reference chain: JsonTraps$Shipment["shipped"])
with JavaTimeModule and ISO dates:
{"id":"S-3","shipped":"2026-11-02"}
- The strict format failed with
onUnrecognizedPropertyException . Jackson'scurrency is on by default, so a partner adding a field to its JSON breaks every consumer.FAIL_ON_UNKNOWN_PROPERTIES - With
, the extra field was ignored and the payment was read. For messages from other teams, this is usually the right setting.setDisableFeatures("FAIL_ON_UNKNOWN_PROPERTIES") - Marshalling a
without help failed withLocalDate , and the message names the fix: the moduleInvalidDefinitionException .jackson-datatype-jsr310 - With
andsetModuleClassNames(".../JavaTimeModule") disabled, the date came out asWRITE_DATES_AS_TIMESTAMPS , the ISO format other systems expect."2026-11-02"
The Java time module is a separate jar, jackson-datatype-jsr310ClassNotFoundException: com.fasterxml.jackson.datatype.jsr310.JavaTimeModulecamel.dataformat.jackson.auto-discover-object-mapper=trueObjectMapperallowUnmarshallTypeCamelJacksonUnmarshalType
XML with JAXB
JAXB maps XML elements and attributes to Java fields by annotation. The invoice class has an attribute and two elements; the program marshals one invoice with pretty printing and unmarshals another from text:
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
public class XmlJaxb {
@XmlRootElement(name = "invoice")
@XmlAccessorType(XmlAccessType.FIELD)
public static class Invoice {
@XmlAttribute
String number;
@XmlElement
String customer;
@XmlElement
double total;
public Invoice() {
}
Invoice(String number, String customer, double total) {
this.number = number;
this.customer = customer;
this.total = total;
}
@Override
public String toString() {
return "Invoice[number=" + number + ", customer=" + customer + ", total=" + total + "]";
}
}
static class Routes extends RouteBuilder {
private final JaxbDataFormat jaxb;
Routes(JaxbDataFormat jaxb) {
this.jaxb = jaxb;
}
@Override
public void configure() {
from("direct:toXml").marshal(jaxb).convertBodyTo(String.class);
from("direct:fromXml").unmarshal(jaxb);
}
}
public static void main(String[] args) throws Exception {
JaxbDataFormat jaxb = new JaxbDataFormat(JAXBContext.newInstance(Invoice.class));
jaxb.setPrettyPrint(true);
jaxb.setEncoding("UTF-8");
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes(jaxb));
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
String xml = template.requestBody("direct:toXml", new Invoice("INV-7", "Acme", 99.5),
String.class);
System.out.println("marshal:\n" + xml);
Object back = template.requestBody("direct:fromXml",
"<invoice number=\"INV-8\"><customer>Globex</customer><total>12.0</total></invoice>");
System.out.println("unmarshal: " + back);
camel.stop();
}
}
marshal:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<invoice number="INV-7">
<customer>Acme</customer>
<total>99.5</total>
</invoice>
unmarshal: Invoice[number=INV-8, customer=Globex, total=12.0]
- The
field became the attributenumber , andnumber="INV-7" andcustomer became child elements, as their annotations say.total added the line breaks and indentation, and the XML declaration names UTF-8, set withsetPrettyPrint(true) .setEncoding - Unmarshalling read the attribute and both elements back into a new
, using the public no-argument constructor that JAXB requires. Records do not work with JAXB for that reason.Invoice
Camel 4 uses Jakarta XML Binding, with annotations in jakarta.xml.bind.annotationjavax.xml.bindJAXBContextjaxb("com.example.invoices")ObjectFactoryjaxb.indexJAXBContext
CSV with Commons CSV
camel-csv reads and writes CSV without any classes, as lists or maps. The input has a header row and a quoted field that contains a comma, and the output uses a semicolon as the delimiter, as many European spreadsheet exports do:
import java.util.List;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.csv.CsvDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
public class CsvFormat {
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:rows").unmarshal().csv();
CsvDataFormat withHeader = new CsvDataFormat();
withHeader.setUseMaps(true);
from("direct:maps").unmarshal(withHeader);
CsvDataFormat semicolons = new CsvDataFormat();
semicolons.setDelimiter(';');
semicolons.setHeader(new String[] {"sku", "name", "price"});
from("direct:write").marshal(semicolons).convertBodyTo(String.class);
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
String csv = "sku,name,price\nB-1,\"Book, hardcover\",19.99\nL-2,Lamp,35.00\n";
List<?> rows = template.requestBody("direct:rows", csv, List.class);
System.out.println("rows as lists:");
rows.forEach(row -> System.out.println(" " + row));
List<?> maps = template.requestBody("direct:maps", csv, List.class);
System.out.println("useMaps, first line as header:");
maps.forEach(map -> System.out.println(" " + map));
List<Map<String, Object>> products = List.of(
Map.of("sku", "D-3", "name", "Desk; oak", "price", "250.00"),
Map.of("sku", "C-4", "name", "Chair", "price", "80.00"));
System.out.println("marshal maps with ';' as delimiter:");
System.out.print(template.requestBody("direct:write", products, String.class));
camel.stop();
}
}
rows as lists:
[sku, name, price]
[B-1, Book, hardcover, 19.99]
[L-2, Lamp, 35.00]
useMaps, first line as header:
{sku=B-1, name=Book, hardcover, price=19.99}
{sku=L-2, name=Lamp, price=35.00}
marshal maps with ';' as delimiter:
sku;name;price
D-3;"Desk; oak";250.00
C-4;Chair;80.00
- By default, each line became a list of strings, and the header line
was just the first row. The quoted[sku, name, price] stayed one field, since the parser follows CSV quoting rules."Book, hardcover" - With
, the first line was used as the header, and each following line became a map from column name to value.setUseMaps(true) - Marshalling maps wrote the header from
, then one line per map in that column order.setHeader contains the delimiter, so the format quoted it. The values come out in header order, althoughDesk; oak has no order of its own.Map.of
Every value is a String19.99split(body().tokenize("\n")).streaming()
Typed records with Bindy
Bindy binds flat files to annotated classes: CSV with @CsvRecord@FixedLengthRecord
import java.math.BigDecimal;
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.apache.camel.dataformat.bindy.annotation.FixedLengthRecord;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.dataformat.bindy.fixed.BindyFixedLengthDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
public class BindyRecords {
@CsvRecord(separator = ",", skipFirstLine = true)
public static class Product {
@DataField(pos = 1)
String sku;
@DataField(pos = 2)
String name;
@DataField(pos = 3, precision = 2)
BigDecimal price;
@Override
public String toString() {
return "Product[" + sku + ", " + name + ", " + price + "]";
}
}
@FixedLengthRecord(length = 21)
public static class Transfer {
@DataField(pos = 1, length = 8)
String account;
@DataField(pos = 9, length = 10, precision = 2, align = "R", paddingChar = '0')
BigDecimal amount;
@DataField(pos = 19, length = 3)
String currency;
@Override
public String toString() {
return "Transfer[" + account + ", " + amount + ", " + currency + "]";
}
}
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:csv").unmarshal(new BindyCsvDataFormat(Product.class));
from("direct:fixedIn").unmarshal(new BindyFixedLengthDataFormat(Transfer.class));
from("direct:fixedOut").marshal(new BindyFixedLengthDataFormat(Transfer.class))
.convertBodyTo(String.class);
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
String csv = "sku,name,price\nB-1,Book,19.99\nL-2,Lamp,35\n";
Object products = template.requestBody("direct:csv", csv);
System.out.println("two CSV lines -> " + products.getClass().getSimpleName() + " "
+ products);
Object single = template.requestBody("direct:csv", "sku,name,price\nB-1,Book,19.99\n");
System.out.println("one CSV line -> " + single.getClass().getSimpleName() + " "
+ single);
Object transfer = template.requestBody("direct:fixedIn", "ACC000420000123.45EUR");
System.out.println("fixed length -> " + transfer);
Object line = template.requestBody("direct:fixedOut", List.of(transfer), String.class);
System.out.println("marshal back -> [" + line.toString().strip() + "]");
camel.stop();
}
}
two CSV lines -> ArrayList [Product[B-1, Book, 19.99], Product[L-2, Lamp, 35.00]]
one CSV line -> Product Product[B-1, Book, 19.99]
fixed length -> Transfer[ACC00042, 123.45, EUR]
marshal back -> [ACC000420000123.45EUR]
- Two CSV lines became an
of twoArrayList objects, withProduct dropping the header. The priceskipFirstLine = true became35 , because35.00 sets the scale of theprecision = 2 .BigDecimal - One CSV line became a single
, not a list with one element. Code that always casts the body toProduct works in testing with several lines and fails in production on a file with one; convert withList , or handle both.getBody(List.class) - The fixed-length line was cut by position: characters 1 to 8 are the account, 9 to 18 the amount, 19 to 21 the currency, giving
.Transfer[ACC00042, 123.45, EUR] - Marshalling the transfer produced the same 21 characters, with the amount right-aligned and padded with zeros, as
andalign = "R" say.paddingChar = '0'
Fixed-length formats are still common in banking and with mainframes, where every field has a set width. Bindy checks the record length: a 20-character line fails with Size of the record: 20 is not equal to the value provided in the model: 21
A custom data format, and chaining formats
When no module fits, implement DataFormatkey=valueMap
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.support.service.ServiceSupport;
public class CustomFormat {
static class KeyValueFormat extends ServiceSupport implements DataFormat {
@Override
public void marshal(Exchange exchange, Object graph, OutputStream stream)
throws Exception {
Map<?, ?> map = exchange.getContext().getTypeConverter()
.mandatoryConvertTo(Map.class, graph);
String text = map.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("\n", "", "\n"));
stream.write(text.getBytes(StandardCharsets.UTF_8));
}
@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
Map<String, String> map = new LinkedHashMap<>();
String text = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
for (String line : text.split("\n")) {
if (!line.isBlank()) {
String[] parts = line.split("=", 2);
map.put(parts[0].strip(), parts[1].strip());
}
}
return map;
}
}
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:kvToJson")
.unmarshal(new KeyValueFormat())
.process(e -> System.out.println(" after unmarshal: "
+ e.getMessage().getBody().getClass().getSimpleName() + " "
+ e.getMessage().getBody()))
.marshal(new JacksonDataFormat())
.convertBodyTo(String.class);
from("direct:jsonToKv")
.unmarshal(new JacksonDataFormat(LinkedHashMap.class))
.marshal(new KeyValueFormat())
.convertBodyTo(String.class);
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("key=value text to JSON:");
System.out.println(" " + template.requestBody("direct:kvToJson",
"host = db.internal\nport = 5432\nuser = app\n", String.class));
System.out.println("JSON to key=value text:");
System.out.print(template.requestBody("direct:jsonToKv",
"{\"queue\":\"orders\",\"retries\":3}", String.class));
camel.stop();
}
}
key=value text to JSON:
after unmarshal: LinkedHashMap {host=db.internal, port=5432, user=app}
{"host":"db.internal","port":"5432","user":"app"}
JSON to key=value text:
queue=orders
retries=3
read the three lines into aunmarshal , keeping their order and trimming the spaces aroundLinkedHashMap .= then wrote the map as JSON. All values are strings, includingmarshal(new JacksonDataFormat()) , because the text format has no types."5432"- In the other direction, Jackson read the JSON into a
, and the custom format wrote one line per entry. The numberLinkedHashMap became the text3 .retries=3
The class extends ServiceSupportDataFormatServicedoStartmarshal().custom("keyValue")
Choosing a data format
| Input or output | Use | Watch out for |
|---|---|---|
| JSON to typed objects | JacksonDataFormat(Type.class)setUseList | Unknown fields fail by default; Java time needs a module |
| JSON for quick field checks | unmarshal().json()Map | No types, numbers as Jackson chooses |
| XML with a schema | JAXB with classes generated from the XSD | jakarta |
| CSV with changing columns | camel-csv with setUseMaps(true) | All values are strings |
| CSV or fixed-length to typed records | Bindy | One line gives an object, several give a list |
| A format with no module | Your own DataFormat | Keep it thread-safe |
Unmarshal as early as possible in a route and marshal as late as possible, so that the steps in between work with typed objects. Errors from data formats are ordinary exceptions, so a dead letter channel or an onException