Pages

2014-08-14

Java EE: Parsing JSON data with the Streaming API

In the last article, we saw how to generate JSON data from our Java code with the Streaming API. In this section, we will see how we can read and parse the existing JSON data we receive from a stream. The following code sample illustrates how to do this:

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 void parseJson() {
      StringReaderstringReader = new StringReader(jsonStr);
      JsonParserjsonParser = Json.createParser(stringReader);
      Map<String, String> keyValueMap = new HashMap<>();
      String key = null;
      String value = null;
      while (jsonParser.hasNext()) {
            JsonParser.Event event = jsonParser.next();
            if (event.equals(Event.KEY_NAME)) {
                  key = jsonParser.getString();
            } else if (event.equals(Event.VALUE_STRING)) {
                  value = jsonParser.getString();
           }
           keyValueMap.put(key, value);
       }
       customer.setFirstName(keyValueMap.get("firstName"));
       customer.setLastName(keyValueMap.get("lastName"));
       customer.setEmail(keyValueMap.get("email"));
  }
}

No comments:

Post a Comment