Running your first JSON-B code
JSON-B is an API for converting Java objects to/from JSON messages in a standardized way. It defines a default mapping algorithm to convert Java classes to JSON and still lets you customize your own algorithms.
With JSON-B, Java EE now has a complete set of tools to work with JSON, such as JSON API, and JSON-P. No third-party frameworks are needed anymore (although you are still free to use them).
This quick recipe will show you how to use JSON-B to convert a Java object to and from a JSON message.
Getting ready
Let's add our dependencies to the project:
<dependencies> <dependency> <groupId>org.eclipse</groupId> <artifactId>yasson</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.1</version> </dependency> </dependencies>
How to do it...
- Let's create a
User
class as a model for our JSON message:
public class User { private String name; private String email; public User(){ } public User(String name, String email) { this.name = name; this.email = email; } @Override public String toString() { return "User{" + "name=" + name + ", email=" + email + '}'; } //DON'T FORGET THE GETTERS AND SETTERS //THIS RECIPE WON'T WORK WITHOUT THEM }
- Then, let's create a class to use JSON-B to transform an object:
public class JsonBUser { public static void main(String[] args) throws Exception { User user = new User("Elder", "[email protected]"); Jsonb jb = JsonbBuilder.create(); String jsonUser = jb.toJson(user); User u = jb.fromJson(jsonUser, User.class); jb.close(); System.out.println("json: " + jsonUser); System.out.println("user: " + u); } }
The result printed is:
json: {"email":"[email protected]","name":"Elder"} user: User{name=Elder, [email protected]}
The first line is the object transformed into a JSON string. The second is the same string converted into an object.
How it works...
It uses the getters and setters defined in the User
class to transform both ways and that's why they are so important.
See also
- You can stay tuned with everything related to JSON-B at http://json-b.net/
- The source code of this recipe is at https://github.com/eldermoraes/javaee8-cookbook/tree/master/chapter01/ch01-jsonb