Search in sources :

Example 1 with JsonParser

use of io.vertx.core.parsetools.JsonParser in project vertx-examples by vert-x3.

the class JsonStreamingExample method start.

@Override
public void start() throws Exception {
    vertx.fileSystem().open("large.json", new OpenOptions(), ar -> {
        if (ar.succeeded()) {
            AsyncFile asyncFile = ar.result();
            AtomicInteger counter = new AtomicInteger();
            // Here a Json streaming parser is created wrapping an AsyncFile
            // JsonParser is a ReadStream of JsonEvent and can wrap any ReadStream of Buffer
            JsonParser jsonParser = JsonParser.newParser(asyncFile);
            // We want to parse a giant array of small obects so we switch the parser to object-value mode
            // The parser will then emit objects inside the array as a single value event
            // This is pretty convenient for the developer
            jsonParser.objectValueMode().exceptionHandler(t -> {
                t.printStackTrace();
                asyncFile.close();
            }).endHandler(v -> {
                System.out.println("Done!");
                asyncFile.close();
            }).handler(event -> {
                // In object-value mode the event should always be of type "VALUE"
                if (event.type() == VALUE) {
                    // Use mapTo to map the JSON obect to a Java class
                    DataPoint dataPoint = event.mapTo(DataPoint.class);
                    // Let's not log all objects from this giant file...
                    if (counter.incrementAndGet() % 100 == 0) {
                        System.out.println("DataPoint = " + dataPoint);
                    }
                }
            });
        } else {
            ar.cause().printStackTrace();
        }
    });
}
Also used : OpenOptions(io.vertx.core.file.OpenOptions) AsyncFile(io.vertx.core.file.AsyncFile) OpenOptions(io.vertx.core.file.OpenOptions) JsonEventType(io.vertx.core.parsetools.JsonEventType) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractVerticle(io.vertx.core.AbstractVerticle) JsonParser(io.vertx.core.parsetools.JsonParser) Runner(io.vertx.example.util.Runner) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncFile(io.vertx.core.file.AsyncFile) JsonParser(io.vertx.core.parsetools.JsonParser)

Aggregations

AbstractVerticle (io.vertx.core.AbstractVerticle)1 AsyncFile (io.vertx.core.file.AsyncFile)1 OpenOptions (io.vertx.core.file.OpenOptions)1 JsonEventType (io.vertx.core.parsetools.JsonEventType)1 JsonParser (io.vertx.core.parsetools.JsonParser)1 Runner (io.vertx.example.util.Runner)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1