This post explains how to read json data as a stream. The previous post explains the same using JsonReader. The difference is that to use JsonReader we need to build the entire object (which represents json data) in memory. Whereas with JsonParser we dont need to build the entire object. The below code explains how to read the below json data and print to console.
Data
{
"firstName": "Duke",
"lastName": "Java",
"age": 18,
"streetAddress": "100 Internet Dr",
"city": "JavaTown",
"state": "JA",
"postalCode": "12345",
"phoneNumbers": [
{ "Mobile": "111-111-1111" },
{ "Home": "222-222-2222" }
]
}
Code
package objectmodel;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
public class Example8 {
public static void main(String[] args) {
try(FileReader fr = new FileReader("E:\\Projects\\JavaProjects\\JavaJSONProject\\jsondata.txt");) {
JsonParser jsonParser = Json.createParser(fr);
while(jsonParser.hasNext()) {
Event event = jsonParser.next();
switch (event) {
case START_OBJECT: System.out.println("Object Started");
break;
case END_OBJECT: System.out.println("Object Ended");
break;
case START_ARRAY: System.out.println("Array Started");
break;
case END_ARRAY: System.out.println("Array Ended");
break;
case KEY_NAME: System.out.print("Key Started:");
System.out.print(jsonParser.getString()+"\n");
break;
case VALUE_FALSE:
case VALUE_NULL:
case VALUE_TRUE:
case VALUE_NUMBER:
case VALUE_STRING: System.out.print("Value Started:");
System.out.print(jsonParser.getString()+"\n");
break;
default:
break;
}
}
jsonParser.close();
} catch(FileNotFoundException excep) {
excep.printStackTrace();
} catch(IOException excep) {
excep.printStackTrace();
}
}
}
Output
Object Started
Key Started:firstName
Value Started:Duke
Key Started:lastName
Value Started:Java
Key Started:age
Value Started:18
Key Started:streetAddress
Value Started:100 Internet Dr
Key Started:city
Value Started:JavaTown
Key Started:state
Value Started:JA
Key Started:postalCode
Value Started:12345
Key Started:phoneNumbers
Array Started
Object Started
Key Started:Mobile
Value Started:111-111-1111
Object Ended
Object Started
Key Started:Home
Value Started:222-222-2222
Object Ended
Array Ended
Object Ended
The json parser reads the json data in pull parsing model. In this model the application ask the parser for next element by calling next() method. It returns one of the below events to indicate the type of the element read next.
START_OBJECT //when found {
END_OBJECT //when found }
START_ARRAY //when found [
END_ARRAY //when found ]
KEY_NAME //when key is found
VALUE_FALSE //when value is found
VALUE_NULL //when value is found
VALUE_TRUE //when value is found
VALUE_NUMBER //when value is found
VALUE_STRING //when value is found
You can print the key using getString() and the value with data type specific get methods available in JsonParser class.