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 object with fields. A data format is the converter between the two, in both directions:

  • unmarshal: wire format to Java. unmarshal(json) reads the body as bytes or text and replaces it with an object.
  • marshal: Java to wire format. marshal(json) takes the object in the body and replaces it with the encoded bytes.

Each data format implements one interface, org.apache.camel.spi.DataFormat, with a marshal(Exchange, Object, OutputStream) and an unmarshal(Exchange, InputStream) method. Camel opens the streams, calls the method and puts the result in the body. Because a data format is also a Camel Service, it is started with the route, which is when configuration errors such as a missing class show up.

Common Camel data formats
FormatModuleLibraryBest for
JSONcamel-jacksonJackson 2 (2.21 here)REST APIs and events
JSONcamel-jackson3 (since Camel 4.19)Jackson 3Applications that have moved to Jackson 3
XMLcamel-jaxbJakarta XML Binding 4XML with a schema or annotated classes
CSVcamel-csvApache Commons CSVRows as lists or maps, without classes
CSV, fixed length, key-valuecamel-bindyAnnotations on your classesTyped records from flat files
Your ownYour codeDataFormat interfaceFormats with no Camel module

A data format differs from a type converter: a type converter turns one Java type into another, such as String to Integer, and is chosen automatically, while a data format is chosen explicitly in the route and knows a document format. The examples run with Camel 4.23 on Java 21, with camel-main, the core components and the modules named in each section.

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:

Java
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();
    }
}
Output
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}
  • unmarshal with new JacksonDataFormat(Order.class) produced an Order record. Jackson 2.12 and later bind records through their canonical constructor, so no setters or annotations are needed.
  • marshal produced the JSON text again. Right after marshalling, the body was an InputStreamCache, not a String: data formats write to a stream, and Camel's stream caching kept it re-readable. convertBodyTo(String.class) made it text.
  • setUseList(true) read the JSON array as a List of two Order records. Without it, Jackson would try to read an array into a single Order and fail.
  • unmarshal().json() without a type produced a LinkedHashMap. That is handy for quick routing on a field, but it gives up type checking, and numbers arrive as whatever Jackson picks, such as Integer or Double.

camel-jackson uses Jackson 2. Camel 4.19 added camel-jackson3 for Jackson 3, whose core packages moved from com.fasterxml.jackson to tools.jackson; that module is not on this page's classpath, so it was not run here. Pick the one that matches the Jackson version the rest of the application uses, so that shared modules and annotations work with both.

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 is marshalled with and without Jackson's Java time module:

Java
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();
    }
}
Output
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 UnrecognizedPropertyException on currency. Jackson's FAIL_ON_UNKNOWN_PROPERTIES is on by default, so a partner adding a field to its JSON breaks every consumer.
  • With setDisableFeatures("FAIL_ON_UNKNOWN_PROPERTIES"), the extra field was ignored and the payment was read. For messages from other teams, this is usually the right setting.
  • Marshalling a LocalDate without help failed with InvalidDefinitionException, and the message names the fix: the module jackson-datatype-jsr310.
  • With setModuleClassNames(".../JavaTimeModule") and WRITE_DATES_AS_TIMESTAMPS disabled, the date came out as "2026-11-02", the ISO format other systems expect.

The Java time module is a separate jar, jackson-datatype-jsr310; when it is missing, the route fails to start with ClassNotFoundException: com.fasterxml.jackson.datatype.jsr310.JavaTimeModule. In Spring Boot, set camel.dataformat.jackson.auto-discover-object-mapper=true to reuse Spring's ObjectMapper, which already has these modules and settings. One more default is worth keeping: allowUnmarshallType is off, so a message cannot pick its own target class through the CamelJacksonUnmarshalType header, which would be a deserialization risk.

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:

Java
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();
    }
}
Output
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 number field became the attribute number="INV-7", and customer and total became child elements, as their annotations say. setPrettyPrint(true) added the line breaks and indentation, and the XML declaration names UTF-8, set with setEncoding.
  • Unmarshalling read the attribute and both elements back into a new Invoice, using the public no-argument constructor that JAXB requires. Records do not work with JAXB for that reason.

Camel 4 uses Jakarta XML Binding, with annotations in jakarta.xml.bind.annotation; classes generated for Camel 3 with javax.xml.bind imports have to be regenerated or migrated. The data format here was built from a JAXBContext for one class. In the DSL, jaxb("com.example.invoices") takes a package that contains an ObjectFactory or a jaxb.index file, which is what classes generated from an XSD have. Building a JAXBContext is slow, so create the data format once, as here, not per message.

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:

Java
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();
    }
}
Output
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 [sku, name, price] was just the first row. The quoted "Book, hardcover" stayed one field, since the parser follows CSV quoting rules.
  • With setUseMaps(true), the first line was used as the header, and each following line became a map from column name to value.
  • Marshalling maps wrote the header from setHeader, then one line per map in that column order. Desk; oak contains the delimiter, so the format quoted it. The values come out in header order, although Map.of has no order of its own.

Every value is a String; converting 19.99 to a number is up to the route. That suits files whose columns change, or routing that only looks at one column. For typed records, use Bindy, next. For large files, split the CSV with split(body().tokenize("\n")).streaming() before unmarshalling each line, as the splitter page shows, rather than unmarshalling the whole file into one list.

Typed records with Bindy

Bindy binds flat files to annotated classes: CSV with @CsvRecord, fixed-length records with @FixedLengthRecord, and key-value pairs. The program reads products from CSV, once with two lines and once with one, then reads and writes a 21-character bank transfer record:

Java
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();
    }
}
Output
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 ArrayList of two Product objects, with skipFirstLine = true dropping the header. The price 35 became 35.00, because precision = 2 sets the scale of the BigDecimal.
  • One CSV line became a single Product, not a list with one element. Code that always casts the body to List works in testing with several lines and fails in production on a file with one; convert with getBody(List.class), or handle both.
  • 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 align = "R" and paddingChar = '0' say.

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, and a field that cannot be parsed fails with an error naming its position and line. That is the information you need to report bad input back to its sender.

A custom data format, and chaining formats

When no module fits, implement DataFormat yourself. This one reads and writes simple key=value lines. Chained with Jackson, it converts in both directions between that format and JSON, with a Map in between:

Java
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();
    }
}
Output
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
  • unmarshal read the three lines into a LinkedHashMap, keeping their order and trimming the spaces around =.
  • marshal(new JacksonDataFormat()) then wrote the map as JSON. All values are strings, including "5432", because the text format has no types.
  • In the other direction, Jackson read the JSON into a LinkedHashMap, and the custom format wrote one line per entry. The number 3 became the text retries=3.

The class extends ServiceSupport because DataFormat extends Service; override doStart to set up expensive objects once. Keep the methods free of per-call state, since one instance serves every exchange on every thread. To make a custom format usable by name, for example from YAML routes, bind it in the registry and refer to it with marshal().custom("keyValue").

Choosing a data format

Which data format to use
Input or outputUseWatch out for
JSON to typed objectsJacksonDataFormat(Type.class), setUseList for arraysUnknown fields fail by default; Java time needs a module
JSON for quick field checksunmarshal().json() to a MapNo types, numbers as Jackson chooses
XML with a schemaJAXB with classes generated from the XSDjakarta annotations in Camel 4
CSV with changing columnscamel-csv with setUseMaps(true)All values are strings
CSV or fixed-length to typed recordsBindyOne line gives an object, several give a list
A format with no moduleYour own DataFormatKeep 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 clause handles bad input, as the error handling page describes. For Jackson modules outside Camel, see the Jackson modules page.