Perform the following steps to try this recipe:
- We first create a User class with some customization (the details follow):
public class User {
private Long id;
@JsonbProperty("fullName")
private String name;
private String email;
@JsonbTransient
private Double privateNumber;
@JsonbDateFormat(JsonbDateFormat.DEFAULT_LOCALE)
private Date dateCreated;
public User(Long id, String name, String email,
Double privateNumber, Date dateCreated) {
this.id = id;
this.name = name;
this.email = email;
this.privateNumber = privateNumber;
this.dateCreated = dateCreated;
}
private User(){
}
//DO NOT FORGET TO IMPLEMENT THE GETTERS AND SETTERS
}
- Here, we use UserView to return the user JSON to the UI:
@ViewScoped
@Named
public class UserView implements Serializable{
private String json;
public void loadUser(){
long now = System.currentTimeMillis();
User user = new User(now,
"User" + now,
"user" + now + "@eldermoraes.com",
Math.random(),
new Date());
Jsonb jb = JsonbBuilder.create();
json = jb.toJson(user);
try {
jb.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
}
- We add a JSF page just to show the results:
<h:body>
<h:form>
<h:commandButton type="submit" action="#{userView.loadUser()}"
value="Load User" />
<br />
<h:outputLabel for="json" value="User JSON" />
<br />
<h:inputTextarea id="json" value="#{userView.json}"
style="width: 300px; height: 300px;" />
</h:form>
</h:body>