playframework Java - Working with JSON Conversion between JSON and Java objects (basic)


Example

By default, Jackson (the library Play JSON uses) will try to map every public field to a json field with the same name. If the object has getters/setters, it will infer the name from them. So, if you have a Book class with a private field to store the ISBN and have get/set methods named getISBN/setISBN, Jackson will

  • Create a JSON object with the field "ISBN" when converting from Java to JSON
  • Use the setISBN method to define the isbn field in the Java object (if the JSON object has a "ISBN" field).

Create Java object from JSON

public class Person {
    String id, name;
}

JsonNode node = Json.parse("{\"id\": \"3S2F\", \"name\", \"Salem\"}");
Person person = Json.fromJson(node, Person.class);
System.out.println("Hi " + person.name); // Hi Salem

Create JSON object from Java object

// "person" is the object from the previous example
JsonNode personNode = Json.toJson(person) 

Creating a JSON string from a JSON object

// personNode comes from the previous example
String json = personNode.toString();
// or 
String json = Json.stringify(json);

JSON pretty printing

System.out.println(personNode.toString());
/* Prints:
{"id":"3S2F","name":"Salem"}
*/   

System.out.println(Json.prettyPrint(personNode));
/* Prints:
{
  "id" : "3S2F",
  "name" : "Salem"
}
*/