- 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"]} | |
{"type":"cheeseburguer","drink":"coke","sides":["chips","salad"]}
Read with JsonParse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
type
cheeseburguer
drink
coke
sides
chips
salad