JsonParser and JsonReader - Streaming and Object Readers in Java API for JSON Processing (TOTD #206)


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 =
    new JsonReader(new StringReader("{}"));
JsonObject json = jsonReader.readObject();
{START_OBJECT }END_OBJECT
{
  "apple":"red",
  "banana":"yellow"
}
jsonReader =
    new JsonReader(new StringReader(...));
json = jsonReader.readObject();

{START_OBJECT
  "apple"KEY_NAME:"red"VALUE_STRING,
  "banana"KEY_NAME:"yellow"VALUE_STRING
}
[
  { "apple":"red" },
  { "banana":"yellow" }
]
jsonReader =
    new JsonReader(new StringReader(...));
JsonArray jsonArr = jsonReader.readArray();

[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 =
    new JsonReader(new StringReader(...));
json = jsonReader.readObject();

{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:

Comments:

Hello Arun,

If the Json can have own type. When it can be in vector.and we put under it matrix (or more vectors)(a plus work): its much better as XML nad it's not duplicated, not hard to read a person who don't learn it.It's great!

Posted by Gabor Gossmann on February 20, 2013 at 01:30 AM PST #

Post a Comment:
Comments are closed for this entry.
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today