2. Your First Serializer
With juneau-marshall on the classpath (the project from the previous page
has it), the Json marshaller turns a bean into JSON and back in one call.
Create the bean, src/main/java/com/example/demo/Pet.java. The REST pages reuse it:
package com.example.demo;
public class Pet {
public int id;
public String name;
public Pet() {}
public Pet(int id, String name) { this.id = id; this.name = name; }
}
Then create src/main/java/com/example/demo/Main.java:
package com.example.demo;
import org.apache.juneau.marshall.json.JsonSerializer;
import org.apache.juneau.marshall.marshaller.Json;
import org.apache.juneau.marshall.marshaller.Json5;
public class Main {
public static void main(String[] args) throws Exception {
String json = Json.of(new Pet(1, "Fido")); // {"id":1,"name":"Fido"}
System.out.println(json);
Pet pet = Json.to(json, Pet.class); // back to a bean
System.out.println(pet.name); // Fido
System.out.println(Json5.of(new Pet(1, "Fido"))); // {id:1,name:'Fido'}
JsonSerializer serializer = JsonSerializer.create().sq().build();
System.out.println(serializer.write(new Pet(1, "Fido"))); // {'id':1,'name':'Fido'}
}
}
Run it from the project directory:
mvn compile exec:java -Dexec.mainClass=com.example.demo.Main
Expected output:
{"id":1,"name":"Fido"}
Fido
{id:1,name:'Fido'}
{'id':1,'name':'Fido'}
Import the marshaller classes by name, as above. A wildcard import of both org.apache.juneau.marshall.json.*
and org.apache.juneau.marshall.marshaller.* makes Json ambiguous, because both packages have a class of
that name.
Other formats
Each format has a marshaller with the same of(...) / to(...) methods. Json5 (used in Main above) writes the relaxed,
quote-free JSON dialect, which is handy for logs and tests.
For XML, HTML, YAML, CSV, MessagePack, and the rest, see juneau-marshall.
Configuring a serializer
The marshaller uses a default serializer and parser. When you need different settings, build your own
and reuse it (serializers are thread-safe and cache their class metadata). Main builds one that uses
single quotes:
JsonSerializer serializer = JsonSerializer.create().sq().build();
String json = serializer.write(new Pet(1, "Fido")); // {'id':1,'name':'Fido'}
See Serializers and Parsers for the full set of options.