在微服务中经常使用JSON。让我们修改之前的一个类以产成JSON格式的有效负载:
public class HelloMicroservice extends AbstractVerticle {
@Override
public void start() {
Router router = Router.router(vertx);
router.get("/").handler(this::hello);
router.get("/:name").handler(this::hello);
vertx.createHttpServer().requestHandler(router::accept)
.listen(8080);
}
private void hello(RoutingContext rc) {
String message = "hello";
if (rc.pathParam("name") != null) {
message += " " + rc.pathParam("name");
}
JsonObject json = new JsonObject().put("message", message);
rc.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.end(json.encode());
}
}
Vert.x提供了一个JsonObject类来创建和操作JSON结构。使用此代码,你在浏览器看到的是这样:
- http://localhost:8080----你会看到 {"message": "hello"}
- http://localhost:8080/vert.x-----你会看到{"message": "hello vert.x"}