JsonReader
reads a JSON object or array from an input
source. This provides DOM access to the JSON structure. JsonParser
provides forward, ready-only access to JSON
data in a streaming way. The parser can be created from InputStream
and Reader
. A sample code looks like:JsonParser jsonParser = Json.createParser(new
StringReader(YOUR_STRING_HERE));
Here is a table with code fragments for parsing some common JSON using Object Model and events generated from Streaming API:
JSON | Object Model API | Events from Streaming API |
---|---|---|
{ } | JsonReader jsonReader = | {START_OBJECT }END_OBJECT |
{
"apple":"red",
"banana":"yellow"
} | jsonReader = | {START_OBJECT
"apple"KEY_NAME:"red"VALUE_STRING,
"banana"KEY_NAME:"yellow"VALUE_STRING
} |
[
{ "apple":"red" },
{ "banana":"yellow" }
] | jsonReader = | [START_ARRAY
{START_OBJECT"apple"KEY_NAME:"red"VALUE_STRING
}END_OBJECT,
{START_OBJECT"banana"KEY_NAME:"yellow"VALUE_STRING
}END_OBJECT
]END_ARRAY |
{
"title":"The Matrix",
"year":1999,
"cast":[
"Keanu Reaves",
"Laurence Fishburne",
"Carrie-Anne Moss"
]
} | jsonReader = | {START_OBJECT
"title"KEY_NAME:"The Matrix"VALUE_STRING,
"year"KEY_NAME:1999VALUE_NUMBER,
"cast"KEY_NAME:[START_ARRAY
"Keanu Reaves"VALUE_STRING,
"Laurence Fishburne"VALUE_STRING,
"Carrie-Anne Moss"VALUE_STRING
]END_ARRAY
}END_OBJECT
|
The source code for this sample can be downloaded here, try it with GlassFish 4 b76 or later.
Note, GlassFish b76 has Public Review version of the APIs. But the APIs have evolved since then and an integration is planned in the next few days. So if you are using an older build, the sample code may not work. I'll update the sample code once the bits are integrated.
Here are some more links for you to read further:
- Public Review javadoc
- Latest javadoc
- Reference Implemenation: jsonp.java.net