Overview

libGDX can perform automatic object to JSON serialization and JSON to object deserialization. Four small classes make up the API:

  • JsonWriter: A builder style API for emitting JSON.
  • JsonReader: Parses JSON and builds a DOM of JsonValue objects.
  • JsonValue: Describes a JSON object, array, string, float, long, boolean, or null.
  • Json: Reads and writes arbitrary object graphs using JsonReader and JsonWriter.

To use these classes outside of libgdx, see the JsonBeans project.

Writing Object Graphs

The Json class uses reflection to automatically serialize objects to JSON. For example, here are two classes (getters/setters and constructors omitted):

  1. public class Person {
  2. private String name;
  3. private int age;
  4. private ArrayList numbers;
  5. }
  6. public class PhoneNumber {
  7. private String name;
  8. private String number;
  9. }

Example object graph using these classes:

  1. Person person = new Person();
  2. person.setName("Nate");
  3. person.setAge(31);
  4. ArrayList numbers = new ArrayList();
  5. numbers.add(new PhoneNumber("Home", "206-555-1234"));
  6. numbers.add(new PhoneNumber("Work", "425-555-4321"));
  7. person.setNumbers(numbers);

The code to serialize this object graph:

  1. Json json = new Json();
  2. System.out.println(json.toJson(person));
  3. {numbers:[{class:com.example.PhoneNumber,number:"206-555-1234",name:Home},{class:com.example.PhoneNumber,number:"425-555-4321",name:Work}],name:Nate,age:31}

That is compact, but hardly legible. The prettyPrint method can be used:

  1. Json json = new Json();
  2. System.out.println(json.prettyPrint(person));
  3. {
  4. numbers: [
  5. {
  6. class: com.example.PhoneNumber,
  7. number: "206-555-1234",
  8. name: Home
  9. },
  10. {
  11. class: com.example.PhoneNumber,
  12. number: "425-555-4321",
  13. name: Work
  14. }
  15. ],
  16. name: Nate,
  17. age: 31
  18. }

Note that the class for the PhoneNumber objects in the ArrayList numbers field appears in the JSON. This is required to recreate the object graph from the JSON because ArrayList can hold any type of object. Class names are only output when they are required for deserialization. If the field was ArrayList<PhoneNumber> numbers then class names would only appear when an item in the list extends PhoneNumber. If you know the concrete type or aren’t using generics, you can avoid class names being written by telling the Json class the types:

  1. Json json = new Json();
  2. json.setElementType(Person.class, "numbers", PhoneNumber.class);
  3. System.out.println(json.prettyPrint(person));
  4. {
  5. numbers: [
  6. {
  7. number: "206-555-1234",
  8. name: Home
  9. },
  10. {
  11. number: "425-555-4321",
  12. name: Work
  13. }
  14. ],
  15. name: Nate,
  16. age: 31
  17. }

When writing the class cannot be avoided, an alias can be given:

  1. Json json = new Json();
  2. json.addClassTag("phoneNumber", PhoneNumber.class);
  3. System.out.println(json.prettyPrint(person));
  4. {
  5. numbers: [
  6. {
  7. class: phoneNumber,
  8. number: "206-555-1234",
  9. name: Home
  10. },
  11. {
  12. class: phoneNumber,
  13. number: "425-555-4321",
  14. name: Work
  15. }
  16. ],
  17. name: Nate,
  18. age: 31
  19. }

The Json class can write and read both JSON and a couple JSON-like formats. It supports “JavaScript”, where the object property names are only quoted when needed. It also supports a “minimal” format (the default), where both object property names and values are only quoted when needed.

  1. Json json = new Json();
  2. json.setOutputType(OutputType.json);
  3. json.setElementType(Person.class, "numbers", PhoneNumber.class);
  4. System.out.println(json.prettyPrint(person));
  5. {
  6. "numbers": [
  7. {
  8. "number": "206-555-1234",
  9. "name": "Home"
  10. },
  11. {
  12. "number": "425-555-4321",
  13. "name": "Work"
  14. }
  15. ],
  16. "name": "Nate",
  17. "age": 31
  18. }

Note: By default, the Json class will not write those fields which have values that are identical to a newly constructed instance. If you wish to disable this behavior and include all fields, call json.setUsePrototypes(false);.

Reading Object Graphs

The Json class uses reflection to automatically deserialize objects from JSON. Here is how to deserialize the JSON from the previous examples:

  1. Json json = new Json();
  2. String text = json.toJson(person);
  3. Person person2 = json.fromJson(Person.class, text);

The type passed to fromJson is the type of the root of the object graph. From this, the Json class determines the types of all the fields and all other objects encountered, recursively. The “knownType” and “elementType” of the root can be passed to toJson. This is useful if the type of the root object is not known:

  1. Json json = new Json();
  2. json.setOutputType(OutputType.minimal);
  3. String text = json.toJson(person, Object.class);
  4. System.out.println(json.prettyPrint(text));
  5. Object person2 = json.fromJson(Object.class, text);
  6. {
  7. class: com.example.Person,
  8. numbers: [
  9. {
  10. class: com.example.PhoneNumber,
  11. number: "206-555-1234",
  12. name: Home
  13. },
  14. {
  15. class: com.example.PhoneNumber,
  16. number: "425-555-4321",
  17. name: Work
  18. }
  19. ],
  20. name: Nate,
  21. age: 31
  22. }

To read the JSON as a DOM of maps, arrays, and values, the JsonReader class can be used:

  1. Json json = new Json();
  2. String text = json.toJson(person, Object.class);
  3. JsonValue root = new JsonReader().parse(text);

The JsonValue describes a JSON object, array, string, float, long, boolean, or null.

Customizing Serialization

Usually automatic serialization is sufficient, however there are some classes where automatic serialization is not possible or custom serialization is desired. Serialization may be customized by having the class implement the Json.Serializable interface or by registering a Json.Serializer with the Json instance.

This example uses Json.Serializable to write a phone number as an object with a single field:

  1. static public class PhoneNumber implements Json.Serializable {
  2. private String name;
  3. private String number;
  4. public void write (Json json) {
  5. json.writeValue(name, number);
  6. }
  7. public void read (Json json, JsonValue jsonMap) {
  8. name = jsonMap.child().name();
  9. number = jsonMap.child().asString();
  10. }
  11. }
  12. Json json = new Json();
  13. json.setElementType(Person.class, "numbers", PhoneNumber.class);
  14. String text = json.prettyPrint(person);
  15. System.out.println(text);
  16. Person person2 = json.fromJson(Person.class, text);
  17. {
  18. numbers: [
  19. {
  20. Home: "206-555-1234"
  21. },
  22. {
  23. Work: "425-555-4321"
  24. }
  25. ],
  26. name: Nate,
  27. age: 31
  28. }

The class implementing Json.Serializable must have a zero argument constructor because object construction is done for you. In the write method, the surrounding JSON object has already been written. The read method always receives a JsonValue that represents that JSON object.

Json.Serializer provides more control over what is output, requiring writeObjectStart and writeObjectEnd to be called if you require a JSON object like Json.Serializable. Alternatively, a JSON array or a simple value (string, int, boolean) could be output instead of an object. Json.Serializer also allows the object creation to be customized:

  1. Json json = new Json();
  2. json.setSerializer(PhoneNumber.class, new Json.Serializer<PhoneNumber>() {
  3. public void write (Json json, PhoneNumber number, Class knownType) {
  4. json.writeObjectStart();
  5. json.writeValue(number.name, number.number);
  6. json.writeObjectEnd();
  7. }
  8. public PhoneNumber read (Json json, JsonValue jsonData, Class type) {
  9. PhoneNumber number = new PhoneNumber();
  10. number.setName(jsonData.child().name());
  11. number.setNumber(jsonData.child().asString());
  12. return number;
  13. }
  14. });
  15. json.setElementType(Person.class, "numbers", PhoneNumber.class);
  16. String text = json.prettyPrint(person);
  17. System.out.println(text);
  18. Person person2 = json.fromJson(Person.class, text);

Serialization Methods

Json has many methods to read and write data to the JSON. Write methods without a name string are used to write a value that is not a JSON object field (eg, a string or an object in a JSON array). Write methods that take a name string are used to write a field name and value for a JSON object.

writeObjectStart is used to start writing a JSON object, then values can be written using the write methods that take a name string. When the object is finished, writeObjectEnd must be called:

  1. json.writeObjectStart();
  2. json.writeValue("name", "value");
  3. json.writeObjectEnd();

The writeObjectStart methods that take an actualType and a knownType will write a class field to the JSON if the types differ. This enables the actual type to be known during deserialization. For example, the known type may be java.util.Map but the actual type is java.util.LinkedHashMap (which extends HashMap), so deserialization needs to know the actual type to create.

Writing arrays works in a similar manner, except the values should be written using the write methods that do not take a name string:

  1. json.writeArrayStart();
  2. json.writeValue("value1");
  3. json.writeValue("value2");
  4. json.writeArrayEnd();

The Json class can automatically write Java object fields and values. writeFields writes all fields and values for the specified Java object to the current JSON object:

  1. json.writeObjectStart();
  2. json.writeFields(someObject);
  3. json.writeObjectEnd();

The writeField method writes the value for a single Java object field:

  1. json.writeObjectStart();
  2. json.writeField(someObject, "javaFieldName", "jsonFieldName");
  3. json.writeObjectEnd();

Many of the write methods take an “element type” parameter. This is used to specify the known type of objects in a collection. For example, for a list:

  1. ArrayList list = new ArrayList();
  2. list.add(someObject1);
  3. list.add(someObject2);
  4. list.add(someObject3);
  5. list.add(someOtherObject);
  6. ...
  7. json.writeObjectStart();
  8. json.writeValue("items", list);
  9. json.writeObjectEnd();
  10. {
  11. items: [
  12. { class: com.example.SomeObject, value: 1 },
  13. { class: com.example.SomeObject, value: 2 },
  14. { class: com.example.SomeObject, value: 3 },
  15. { class: com.example.SomeOtherObject, value: four }
  16. ]
  17. }

Here the known type of objects in the list is Object, so each object in the JSON for “items” has a class field that specifies Integer or String. By specifying the element type, Integer is used as the known type so only the last entry in the JSON for “items” has a class field:

  1. json.writeObjectStart();
  2. json.writeValue("items", list, ArrayList.class, Integer.class);
  3. json.writeObjectEnd();
  4. {
  5. items: [
  6. { value: 1 },
  7. { value: 2 },
  8. { value: 3 },
  9. { class: com.example.SomeOtherObject, value: four }
  10. ]
  11. }

For maps, the element type is used for the values. The keys for maps are always strings, a limitation of how object fields are described using JSON.

Note that the Json class uses generics on Java field declarations to determine the element type where possible.

Supported Classes

Note that when using GWT, not all classes are serializable. Json supports the following:

  • POJOs
  • OrderedMap (but not ArrayMap)
  • Array
  • String
  • Float
  • Boolean

Make sure to provide your own de/serializers or mark objects you don’t intend to serialize with the ‘transient’ keyword.

Manual and Event Based Parsing

The JsonReader class reads JSON and has protected methods that are called as JSON objects, arrays, strings, floats, longs, and booleans are encountered. By default, these methods build a DOM out of JsonValue objects. These methods can be overridden to do your own event based JSON handling.

  1. // read something
  2. JsonValue fromJson = new JsonReader().parse(jsonAsString);
  3. nickName = fromJson.getString("nickName");
  4. // ...
  5. // write something
  6. JsonValue toJson = new JsonValue(JsonValue.ValueType.object);
  7. toJson.addChild("name", new JsonValue("some name");
  8. toJson.addChild("age", 12);
  9. // ...
  10. toJson.toJson(JsonWriter.OutputType.json);