Java API for JSON Processing (JSR 353) cleared Public Review unanimously and is on its way to to standardization. There is still Proposed Final Draft and the final vote to come. As per the Java EE 7 schedule, the specification will be final on 4/15/2013. The implementation is already integrated in GlassFish 4 builds.
The API provides an Object Model (like DOM for XML) and Streaming API (like StAX for XML) to parse and generate JSON structure. Here is a table that provide code fragments for generating some common JSON:
JSON | Object Model API | Streaming API |
---|---|---|
{ } | JsonObject jsonObject =
new JsonWriter(System.out) | JsonGeneratorFactory factory =
JsonGenerator gen =
gen.writeStartObject().writeEnd(); |
{
"apple":"red",
"banana":"yellow"
} | new JsonObjectBuilder()
.add("apple", "red")
.add("banana", "yellow")
.build(); | gen.writeStartObject()
.write("apple", "red")
.write("banana","yellow")
.writeEnd(); |
[
{ "apple":"red" },
{ "banana":"yellow" }
] | JsonArray jsonArray = new
JsonArrayBuilder()
.add(new JsonObjectBuilder()
.add(new JsonObjectBuilder()
.build(); | gen.writeStartArray()
.writeStartObject()
.write("apple", "red")
.writeEnd()
.writeStartObject()
.write("banana", "yellow")
.writeEnd()
.writeEnd(); |
{
"title":"The Matrix",
"year":1999,
"cast":[
"Keanu Reaves",
"Laurence Fishburne",
"Carrie-Anne Moss"
]
} | new JsonArrayBuilder()
.add(new JsonObjectBuilder()
.add("title", "The Matrix")
.add("year", 1999)
.add("cast", new JsonArrayBuilder()
.add("Keanu Reaves")
.add("Laurence Fishburne")
.add("Carrie-Anne Moss")))
.build(); | gen.writeStartObject()
.write("title", "The
Matrix")
.write("year", 1999)
.writeStartArray("cast")
.write("Keanu Reaves")
.write("Laurence Fishburne")
.write("Carrie-Anne Moss")
.writeEnd()
.writeEnd(); |
The source code for this sample can be downloaded here, try it with GlassFish 4 b76 or later.
Here are some more links for you to read further:
- Public Review javadoc
- Latest javadoc
- Reference Implemenation: jsonp.java.net