Building a HTTP Endpoint with Eclipse Vert.x

cescoffier
3,307 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Producing JSON

JSON is everywhere Today. So let's jump into the train too and produce a JSON result. To do this, Vert.x provides:

  1. the Json class providing object mapping methods,
  2. the JsonObject and JsonArray allowing to create and manipulate JSON structures.

We are going to use this second approach to return something like:

{
    "message": "hello"
}

This object can be easily created using: new JsonObject().put("message", "hello"). Then, we just need to encode this JSON structure into the HTTP response:

Producing JSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package io.vertx.playground;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
public class HttpServerJsonExample {
public static void main(String... args) {
Vertx vertx = Vertx.vertx();
vertx.createHttpServer()
.requestHandler(req -> {
JsonObject json = new JsonObject()
.put("message", "hello");
req.response()
.putHeader("Content-Type", "application/json; charset=UTF8")
.end(json.encodePrettily());
})
.listen(8080);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content