java - Vert.x,RoutingContext无法接收json数组

标签 java vert.x vertx-verticle


我在接收 json 数组时遇到问题。

发送 JSON 是:

[
     {
        "name": "Account 3",
        "type": 2,
        "active": true
     },
     {
         "name": "Account 4",
         "type": 1,
         "active": true
     },
     {
         "name": "Account 5",
         "type": 0,
         "active": true
     }
]


错误是:

Mar 31, 2018 6:28:37 PM io.vertx.ext.web.impl.RoutingContextImplBase
SEVERE: Unexpected exception in route
io.vertx.core.json.DecodeException: Failed to decode: Cannot deserialize instance of `java.util.LinkedHashMap` out of START_ARRAY token

租户安全类:

class TenantSwitcherHandler(val vertx: Vertx) {
fun switchTenant(routingContext: RoutingContext) {
    val tenantId: String? = routingContext.request().headers().get(CommonConstants.HEADER_TENANT)
    if (tenantId.isNullOrEmpty()) {
        routingContext.response().setStatusCode(HttpResponseStatus.UNAUTHORIZED.code()).end(ErrorMessages.CANT_FIND_X_TENANT_ID_HEADER.value())
        return
    } else {
        vertx.eventBus().send(CommonConstants.SWITCH_TENANT, tenantId)
        routingContext.next()
    }
}
}

执行routingContext.next()时发生错误... 我该如何解决这个问题?

P.S.:TenantSwitcherHandler 类注册为安全处理程序,根据 X-TENANT-ID header 值将指针切换到数据库

最佳答案

这个问题实际上与您发布的代码无关,而是与您的下一条路线有关。
您发送的数组不是有效的 JSON 对象。
您可以:

  1. 从您的客户端打包发送:{"array":[...]}
  2. 改用getBodyAsJsonArray

这里有一些您可以使用的代码: 最终 Vertx vertx = Vertx.vertx();

    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    router.post("/").handler(c -> {
            JsonObject json = c.getBodyAsJson();
            // If you want to read JSON array, use this
            // JsonArray jsonArray = c.getBodyAsJsonArray();

            c.response().end(json.toString());
        }
    );
    vertx.createHttpServer().requestHandler(router::accept).listen(8443);


    System.out.println("Server started");
    WebClient client = WebClient.create(vertx);

    // This will succeed
    client.request(HttpMethod.POST, 8443, "localhost", "/").
            sendBuffer(Buffer.buffer("{}"), h -> {
                System.out.println(h.result().bodyAsString());
            });

    // This will fail
    client.request(HttpMethod.POST, 8443, "localhost", "/").
            sendBuffer(Buffer.buffer("[]"), h -> {
                System.out.println(h.result().bodyAsString());
    });

关于java - Vert.x,RoutingContext无法接收json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49588402/

相关文章:

java - 如何使用 vert.x java api 将服务器通知(推送通知)发送给客户端

java - Java中嵌套if else逻辑错误

kotlin - 我想用 Vertx 发送一个文件部分图像,我想用 Postman 之类的代码复制这个案例

java - 应用程序上下文+ Autowiring

java - 如何解决 Vertx 阻塞 DNS 问题

java - MDC 记录 Vertx

java - 将 Thymeleaf TemplateEngine 与 Vert.x 3.9 结合使用

vert.x - Vertx.deployVerticle 不调用提供的完成处理程序

java - 非法选项: -cacerts for keytool in gitlab-ci with gradle:jdk8

java - 如何使每次保存屏幕截图时保存的文件不同