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



假设我们有这个:

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

您可以使用JsonObject.mapTo(Class),例如:

JsonObject product = ctx.getBodyAsJson();
Product instance = product.mapTo(Product.class);

更新

您可以通过操作与 Json 类关联的ObjectMapper实例来自定义 (反)序列化行为。 下面是一些示例:

// 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

最新更新