我收到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
TenantSecurity类:
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标头值将指针切换到数据库
答案 0 :(得分:1)
此问题与您发布的代码无关,实际上与您下一条路线有关 您发送的数组不是有效的JSON对象 你可以:
{"array":[...]}
getBodyAsJsonArray
代替以下是您可以使用的一些代码: 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());
});