Skip to main content

NG Body Converters

A BodyConverter<T> turns an object passed to RestRequest.body(Object) into a transport body before the client falls back to the default serializer.

public interface BodyConverter<T> {
boolean canConvert(Object o);
TransportBody convert(Object o) throws Exception;

static <T> BodyConverter<T> of(Class<T> type, ThrowingConverter<T> fn);
}

Built-in converters​

RestClient.DEFAULT_BODY_CONVERTERS handles, in order: HttpBody, InputStream, byte[], and File. Anything else is serialized by the client's default serializer.

Registering your own​

RestClient client = RestClient.builder()
.bodyConverter(BodyConverter.of(Path.class, p -> TransportBody.of(FileBody.of(p.toFile()))))
.build();

client.put("/upload").body(Path.of("data.bin")).run().close();
Builder methodEffect
bodyConverter(...)Prepends converters, so they win over the defaults and keep them as fallbacks.
bodyConverters(...)Replaces the whole list, including the built-in converters.

The first converter whose canConvert returns true is used.

When to use one​

  • Sending a type you do not want routed through Juneau marshalling (streams, files, pre-encoded data).
  • Adding a transport body for a domain type (for example, a buffer with a specific content type).

For serializing beans, prefer configuring a serializer rather than writing a converter.