JSON 5
The Json5Serializer class can be used to serialized POJOs into JSON 5 notation.
JSON 5 is similar to JSON except for the following:
- JSON attributes are only quoted when necessary.
- Uses single-quotes for quoting.
Examples
// Some free-form JSON.
JsonMap map = JsonMap.of(
"foo", "x1",
"_bar", "x2",
" baz ", "x3",
"123", "x4",
"return", "x5",
"", "x6"
);
// Serialized to standard JSON
{
"foo": "x1",
"_bar": "x2",
" baz ": "x3",
"123": "x4",
"return": "x5",
"": "x6"
}
// Serialized to JSON5
{
foo: 'x1',
_bar: 'x2',
' baz ': 'x3', // Quoted due to embedded spaces.
'123': 'x4', // Quoted to prevent confusion with number.
'return': 'x5', // Quoted because it's a keyword.
'': 'x6' // Quoted because it's an empty string.
}
The advantage to JSON 5 is you can represent it in a Java String in minimal form with minimal escaping. This is particularly useful in cases such as unit testing where you can easily validate POJOs by simplifying them to JSON 5 and do a simple string comparison.
WriterSerializer serializer = Json5Serializer.DEFAULT;
assertEquals("{foo:'bar',baz:123}", serializer.toString(myPojo));
Readable output — the Json5R variant marshaller
For indented, multi-line JSON5 output, use the dedicated
Json5R
variant marshaller (backed by Json5Serializer.DEFAULT_READABLE). It is a first-class Json5 facade, so it
exposes the same static of(...) / to(...) shortcut surface as Json5 itself:
// Compact (default):
String compact = Json5.of(myPojo); // {foo:'bar',baz:123}
// Readable (indented, multi-line):
String pretty = Json5R.of(myPojo);
(This replaces the former Json5.DEFAULT_READABLE constant, removed in 10.0.0.)
See Also
- JSON5L Basics — JSON5 combined with newline-delimited (one document per line) framing.