How to do it...

You need to perform the following steps to try this recipe:

  1. 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

}
  1. 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);

}
}
  1. The result printed is as follows:
 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.10.246