You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache Camel consumes()接受无效JSON,如何开启严格JSON解析模式?

问题描述

我有一个用于创建用户的RESTful端点:

POST /users/new

{
    "id": 1,
    "name": "John Doe"
}

Camel通过consumes()处理请求,并借助Jackson将JSON对象的键转换为消息头,我通过这些消息头存储用户。相关配置如下:

this.restConfiguration()
    .component("netty4-http")
    .bindingMode(RestBindingMode.json)
    .contextPath("/").port(AbstractRestRoute.PORT)
    .enableCORS(true)
    .corsAllowCredentials(true)
    .corsHeaderProperty("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");

this.rest.("/users")
    .post("/new")
        .consumes("application/json")
        .produces("application/json")
        .to("direct:rest:newuser");

该功能正常工作,但有客户端传入了两个用户对象:

POST /users/new

{
    "id": 1,
    "name": "John Doe"
}
{
    "id": 2,
    "name": "Jane Doe"
}

本以为Camel会抛出JSON解析错误,但实际应用处理了请求并忽略了第二个对象,结果与传入单个对象一致。请问能否将Camel设置为严格JSON解析模式以在此场景下抛出错误?

解决方案

要让Camel在遇到多个顶级JSON对象时抛出解析错误,只需开启Jackson的FAIL_ON_TRAILING_TOKENS反序列化特性,具体实现方式如下:

方式一:全局配置(所有REST端点生效)

创建自定义Jackson数据格式并注入到Camel的REST配置中:

// 初始化自定义Jackson格式,开启 trailing tokens 校验
JacksonDataFormat strictJsonFormat = new JacksonDataFormat();
strictJsonFormat.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);

// 配置REST时指定该格式
this.restConfiguration()
    .component("netty4-http")
    .dataFormat("json", strictJsonFormat) // 替换默认JSON解析格式
    .bindingMode(RestBindingMode.json)
    .contextPath("/").port(AbstractRestRoute.PORT)
    .enableCORS(true)
    .corsAllowCredentials(true)
    .corsHeaderProperty("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");

方式二:单个端点配置(仅目标端点生效)

如果只想针对/users/new端点启用严格解析,可以在端点定义中单独指定数据格式:

JacksonDataFormat strictJsonFormat = new JacksonDataFormat();
strictJsonFormat.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);

this.rest.("/users")
    .post("/new")
        .consumes("application/json")
        .produces("application/json")
        .bindingMode(RestBindingMode.off) // 关闭默认绑定
        .to("direct:rest:newuser")
        .setBody().jsonpath("$", strictJsonFormat); // 使用严格格式解析请求体

方式三:Spring Boot配置文件(整合场景)

如果是Spring Boot+Camel的项目,直接通过配置文件开启特性更简便:

# application.properties
camel.jackson.deserialization-fail-on-trailing-tokens=true

验证效果

配置完成后,当客户端传入多个顶级JSON对象时,Jackson会抛出JsonParseException,Camel会自动将其转换为HTTP 400 Bad Request响应,符合严格解析的需求。

注意:FAIL_ON_TRAILING_TOKENS特性从Jackson 2.9版本开始提供,请确保你的依赖版本符合要求。


内容的提问来源于stack exchange,提问作者Rob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:37:29