joi, 23 aprilie 2015

[OmniFaces utilities (2.0)] Encode the given Collection as JSON


[OmniFaces utilities] The encode() method encodes the given object as JSON. This supports the standard types Boolean, Number, CharSequence and Date. If the given object type does not match any of them, then it will attempt to inspect the object as a java bean whereby the public properties (with public getters) will be encoded as a JS object. It also supports Collections, Maps and arrays of them, even nested ones. The Date is formatted in RFC 1123 format, so you can if necessary just pass it straight to new Date() in JavaScript.

Method:
Read more:
Usage:

For example, suppose we have the following bean:

import java.util.Date;
...
public class Player {

 private Boolean righthanded;
 private String name;
 private Integer age;
 private Date birthdate;

 public Player(Boolean righthanded, String name, Integer age, Date birthdate) {
  this.righthanded = righthanded;
  this.name = name;
  this.age = age;
  this.birthdate = birthdate;
 }   
 ...
 // getters and setters
}

And, we define a collection of Players:

List<Player> players = new ArrayList<>(Arrays.asList(
      new Player(true, "Novak Djokovic", 27, new Date()),
      new Player(false, "Rafael Nadal", 28, new Date()),
      new Player(true, "Andy Murray", 27, new Date())));

Now we can encode the players collection into a JSON object:

import org.omnifaces.util.Json;
...
String jsonPlayers = Json.encode(players);

JSON-encoded representation of the given object will be:

[{"age":27,"birthdate":"Thu, 23 Apr 2015 11:54:03 GMT","name":"Novak Djokovic","righthanded":true},{"age":28,"birthdate":"Thu, 23 Apr 2015 11:54:03 GMT","name":"Rafael Nadal","righthanded":false},{"age":27,"birthdate":"Thu, 23 Apr 2015 11:54:03 GMT","name":"Andy Murray","righthanded":true}]

Or, nicely formatted:


Note  Behind the scene, Json#encode() will use:
·         Json#encodeCollection() - since players is a List
·         Json#encodeBean() - since players contains instances of the Player bean
·         the supported Java standard types - since Player bean contains properties of Java standard types

Niciun comentariu:

Trimiteți un comentariu