Pages

2014-08-14

Java EE: Generating JSON data with the Model API

At the heart of the JSON-P Model API is the JsonObjectBuilder class. This class has several overloaded add() methods that can be used to add properties and their corresponding values to the generated JSON data. The following code sample illustrates how to generate JSON data using the Model API:

importimportjavax.inject.Named;
importimportjavax.json.Json;
importimportjavax.json.JsonObject;
importimportjavax.json.JsonReader;
importimportjavax.json.JsonWriter;

@Named
@SessionScoped
public class JsonpBean implements Serializable{
private String jsonStr;
@Inject
private Customer customer;

public String buildJson() {
JsonObjectBuilderjsonObjectBuilder =Json.createObjectBuilder();
JsonObjectjsonObject = jsonObjectBuilder.add("firstName", "ATHIMNI").add("lastName", "Mohamed").add("email", "m.athimni@example.com").build();

StringWriter stringWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stringWriter))
{
   jsonWriter.writeObject(jsonObject);
}
return stringWriter.toString();
}

No comments:

Post a Comment