Sunday, 22 February 2015

JSON Read & Write with Java (part II)

There are 2 API to perform JSON processing:

  • Object model ( JsonReader/JsonWritter)
  • Streaming (JsonParser/ JsonGenerator)

In the previous post we reviewed the use of JSON processing using object model : create objects with JsonBuilder, and I/O actions with JsonReader and JsonWritter.

Today, we will take a look to the other alternative of processing JSON with JsonParse and JsonGenerator.

Remember that working with Json processing requires to import the package javax.json.* (Available if we are working with Java7 enterprise edition). 

Write with JsonGenerator

StringWriter sw = new StringWriter();
JsonGenerator jGenerator = Json.createGenerator(sw);
jGenerator
.writeStartObject()
.write("type", "cheeseburguer")
.write("drink", "coke")
.writeStartArray("sides")
.write("chips")
.write("salad")
.writeEnd()
.writeEnd()
.close();
System.out.println(sw);
//{"type":"cheeseburguer","drink":"coke","sides":["chips","salad"]}
The output will be:
{"type":"cheeseburguer","drink":"coke","sides":["chips","salad"]}

Read with JsonParse

JsonParser jParser = Json.createParser(new StringReader(sw.toString()));
while (jParser.hasNext()) {
Event event = jParser.next();
if (event.equals(Event.KEY_NAME)) {
System.out.println(jParser.getString());
}
if (event.equals(Event.VALUE_STRING)) {
System.out.println(jParser.getString());
}
}
view raw JsonParse.java hosted with ❤ by GitHub
The output will be:
type
cheeseburguer
drink
coke
sides
chips
salad



No comments:

Post a Comment