Pages

2014-08-14

Java EE: Generating JSON data with the Streaming API

The JSON-P Streaming API allows the sequential reading of a JSON object from a stream (a subclass of java.io.OutputStream, or a subclass of java.io.Writer). It is faster and more memory efficient than the Model API. However, the tradeoff is that it is more limited, since the JSON data needs to be read sequentially and we cannot access specific JSON properties directly, the way the Model API allows.

The JSON Streaming API has a JsonGenerator class that we can use to generate JSON data and write it to a stream. This class has several overloaded write() methods which can be used to add properties and their corresponding values to the generated JSON data.

import javax.json.Json;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
@Named
@SessionScoped
public class JsonpBean implements Serializable {
   private String jsonStr;
   @Inject private Customer customer;
   public String buildJson() {
      StringWriter stringWriter = new StringWriter();
      try (JsonGenerator jsonGenerator = Json.createGenerator(stringWriter)) {
         jsonGenerator.writeStartObject(). write("firstName", "ATHIMNI"). write("lastName", "Mohamed").write("email", "m.athimni@example.com").writeEnd();
   return  stringWriter.toString();
   }
}

No comments:

Post a Comment