PlainText
Juneau supports converting POJOs to and from plain text.
Serialization simply uses the object's toString() method (or an ObjectSwap<?,String> swap if one is defined for
the class). Parsing converts text back into a POJO via a static fromString(String) / valueOf(String) method, or a
constructor taking a single String argument (again, honoring any registered swap).
PlainText support is included in juneau-marshall.
| Maven | |
|---|
The relevant classes are:
Media Types
Both the serializer and parser handle text/plain.
Quick Start
The PlainText marshaller provides one-line convenience methods over its default serializer and parser:
// Serialize a POJO to plain text (uses toString()).
String text = PlainText.DEFAULT.of(myPojo);
// Parse plain text back into a POJO.
MyPojo pojo = PlainText.DEFAULT.to(text, MyPojo.class);
Round-Tripping POJOs
Any class that provides a string representation and a way to reconstruct itself from a string can be round-tripped:
public class Temperature {
private final int celsius;
// Used by the parser (single-String constructor).
public Temperature(String value) {
celsius = Integer.parseInt(value.replace("C", ""));
}
// Used by the serializer.
@Override
public String toString() {
return celsius + "C";
}
}
String text = PlainText.DEFAULT.of(new Temperature("20C")); // "20C"
Temperature t = PlainText.DEFAULT.to("20C", Temperature.class);
Serializer / Parser
The underlying serializer and parser can also be used directly via their reusable DEFAULT instances:
String text = PlainTextSerializer.DEFAULT.write(myPojo);
MyPojo pojo = PlainTextParser.DEFAULT.read(text, MyPojo.class);
- Marshallers for the common
of(...)/to(...)marshaller API. - Swaps for replacing non-string types with string equivalents.
- POJO Categories for the categories of objects that can be reconstructed from strings.