Working with JSON streams efficiently (in Java)

后端 未结 1 1671
谎友^
谎友^ 2020-12-21 00:58

I\'ve been using both JSONObject and JSONReader, but ideally I\'m looking for a hybrid :)

In particular, given a stream of JSON objects, part of arbitrarily long JSO

相关标签:
1条回答
  • 2020-12-21 01:14

    There's the javax.json.JSONParser.

    An example that prints out a JSON:

    import javax.json.Json;
    import javax.json.stream.JsonParser;
    ...
    JsonParser parser = Json.createParser(new StringReader(jsonData));
    while (parser.hasNext()) {
       JsonParser.Event event = parser.next();
       switch(event) {
          case START_ARRAY:
          case END_ARRAY:
          case START_OBJECT:
          case END_OBJECT:
          case VALUE_FALSE:
          case VALUE_NULL:
          case VALUE_TRUE:
             System.out.println(event.toString());
             break;
          case KEY_NAME:
             System.out.print(event.toString() + " " +
                              parser.getString() + " - ");
             break;
          case VALUE_STRING:
          case VALUE_NUMBER:
             System.out.println(event.toString() + " " +
                                parser.getString());
             break;
       }
    }
    

    from The Java EE Tutorial 19.4.1 Reading JSON Data Using a Parser. It's part of the JavaEE 7 API but a standalone jar can be gotten from https://jsonp.java.net/download.html.

    0 讨论(0)
提交回复
热议问题