- Jakarta EE Cookbook
- Elder Moraes
- 172字
- 2021-06-24 16:12:39
How to do it...
You need to perform the following steps to try this recipe:
- 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 as follows:
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.
推薦閱讀
- Three.js開發指南:基于WebGL和HTML5在網頁上渲染3D圖形和動畫(原書第3版)
- VMware vSphere 6.7虛擬化架構實戰指南
- Python神經網絡項目實戰
- Big Data Analytics
- INSTANT Django 1.5 Application Development Starter
- C++面向對象程序設計習題解答與上機指導(第三版)
- Kotlin開發教程(全2冊)
- C#程序設計(項目教學版)
- QPanda量子計算編程
- Mastering ASP.NET Core 2.0
- Clojure Web Development Essentials
- Python人工智能項目實戰
- C++程序設計習題與實驗指導
- Java程序設計
- C#從入門到精通(第5版)