Bypass Serialization using `Readers` and `InputStreams`
Juneau serializers treat instances of Readers
and InputStreams
special by simply serializing their contents directly
to the output stream or writer.
This allows you to embed fully customized serializer output.
public class MyBean {
// A bean property that produces raw JSON.
public Reader f1 = new StringReader("{'foo':'bar'}");
}
// Produces "{f1:{'foo':'bar'}}"
String json = Json5.of(new MyBean());
Note that if you're serializing Readers
and InputStreams
, it's up to you to make sure you're producing valid output
(in this case JSON).
A more typical scenario where this is useful is by using swaps to convert POJOs to Readers
whose contents are determined
via the BeanSession.getMediaType() method.
In the following example, we're customizing the JSON output for a particular bean type but leaving all other renditions as-is:
@Swap(MyBeanSwapSometimes.class)
public class MyBean {...}
// A swap that produces specialized output for JSON but default serialization for
// all other media types.
public class MyBeanSwapSometimes extends ObjectSwap {
public Object swap(BeanSession session, MyPojo object) throws Exception {
MediaType mediaType = session.getMediaType();
if (mediaType.hasSubType("json"))
return new StringReader("{myPojo:'foobar'}"); // Custom JSON output
return object; // Otherwise serialize it as a normal bean
}
}
Due to the nature of the RDF serializers, Readers
and InputStreams
are serialized as literals,
not as RDF text.
This is due to the fact that the RDF serializers use a DOM for serialization so we don't have
access to the underlying stream.