How to parse a JSON string using Streaming API in Java?

JavaJSONObject Oriented ProgrammingProgramming

The Streaming API consists of an important interface JsonParser and this interface contains methods to parse JSON in a streaming way and provides forward, read-only access to JSON data. The Json class contains the methods to create parsers from input sources. We can parse a JSON using the static method createParser() of Json class.

Syntax

public static JsonParser createParser(Reader reader)

Example

import java.io.*;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;

public class JSONParseringTest {
   public static void main(String[] args) {
      String jsonString = "{\"name\":\"Adithya\",\"employeeId\":\"115\",\"age\":\"30\"}";
      JsonParser parser = Json.createParser(new StringReader(jsonString));
      while(parser.hasNext()) {
         Event event = parser.next();
         if(event == Event.KEY_NAME) {
            switch(parser.getString()) {
               case "name":
                  parser.next();
                  System.out.println("Name: " + parser.getString());
                  break;
               case "employeeId":
                  parser.next();
                  System.out.println("EmployeeId: " + parser.getString());
                  break;
               case "age":
                  parser.next();
                  System.out.println("Age: " + parser.getString());
                  break;
            }
         }
      }
   }  
}

Output

Name: Adithya
EmployeeId: 115
Age: 30
raja
Published on 22-Oct-2019 08:27:33
Advertisements