上QQ阅读APP看书,第一时间看更新
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", "elder@eldermoraes.com");
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":"elder@eldermoraes.com","name":"Elder"}
user: User{name=Elder, email=elder@eldermoraes.com}
The first line is the object transformed into a JSON string. The second is the same string converted into an object.