Home  >  Article  >  Java  >  How to parse JSON string using streaming API in Java?

How to parse JSON string using streaming API in Java?

王林
王林forward
2023-08-29 18:49:04572browse

How to parse JSON string using streaming API in Java?

The streaming API consists of an important interface JsonParser , which includes parsing JSON in streaming mode and provides Forward, Read-onlyMethods to access JSON data. The Json class contains methods for creating parsers from input sources. We can use the static method createParser() of the Json class to parse JSON.

Grammar

public static JsonParser createParser(Reader reader)

Example

Chinese translation is:

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

The above is the detailed content of How to parse JSON string using streaming API in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete