Home > Java > javaTutorial > body text

How to parse JSON string using streaming API in Java?

王林
Release: 2023-08-29 18:49:04
forward
571 people have browsed it

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)
Copy after login

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;
            }
         }
      }
   }  
}
Copy after login

Output

Name: Adithya
EmployeeId: 115
Age: 30
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template