说我们有这个
Router router = Router.router(vertx);
router.put("/products/:productID").handler(this::handleAddProduct);
这:
private void handleAddProduct(RoutingContext ctx) {
String productID = ctx.request().getParam("productID");
HttpServerResponse response = ctx.response();
JsonObject product = ctx.getBodyAsJson();
products.put(productID, product);
response.end();
}
我的问题是-我们如何才能将ctx.getBodyAsJson()
反序列化为特定的Java类而不是通用的JsonObject
类?
答案 0 :(得分:1)
您可以使用JsonObject.mapTo(Class)
,例如:
JsonObject product = ctx.getBodyAsJson();
Product instance = product.mapTo(Product.class);
更新
您可以通过处理与ObjectMapper
类关联的Json
实例来自定义反序列化行为。这里有一些例子:
// only serialize non-null values
Json.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// ignore values that don't map to a known field on the target type
Json.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
请紧记Json
引用了两个不同的ObjectMapper
:
mapper
和prettyMapper