Search code examples
javavert.xvertx-verticle

Vert.x, RoutingContext can't receive json array



I have a problem with receiving json array.

Sending JSON is:

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


The error is:

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

TenantSecurity class:

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()
    }
}
}

Error occurs while executing routingContext.next()... how can I fix the problem?

P.S.: TenantSwitcherHandler class registered as Security handler, which switches pointer to database according to X-TENANT-ID header value


Solution

  • This problem is not related to the code you posted, actually, but to the next route you have.
    Array you send is not a valid JSON Object.
    You can either:

    1. Send it wrapped from your client: {"array":[...]}
    2. Use getBodyAsJsonArray instead

    Here's some code you can play with: final 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());
        });