将请求正文反序列化为特定类而不是JsonObject

时间:2019-01-28 02:25:26

标签: vert.x

说我们有这个

   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类?

1 个答案:

答案 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