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

Apache Camel Spring DSL中带引号字符串匹配的转义方法

解决Apache Camel Spring DSL中判断JSON消息体的问题

我之前也碰到过类似的坑,Spring XML的特殊字符处理加上Camel Simple表达式的字符串匹配规则,确实容易让转义操作失效。给你几个靠谱的解决办法:

方案1:用CDATA包裹Simple表达式(最稳妥的字符串匹配方式)

Spring XML会解析标签内的特殊字符,比如JSON里的双引号,直接写容易被干扰。把Simple表达式放在<![CDATA[]]>里,XML解析器就会忽略里面的特殊字符,直接把完整表达式传给Camel引擎:

判断以{"status":"OK"}开头

<camel:choice>
    <camel:when>
        <camel:simple><![CDATA[${in.body} startsWith '{"status":"OK"}']]></camel:simple>
    </camel:when>
    <camel:otherwise>
        <!-- 处理其他情况 -->
    </camel:otherwise>
</camel:choice>

判断消息体完全等于{"status":"OK"}

<camel:when>
    <camel:simple><![CDATA[${in.body} == '{"status":"OK"}']]></camel:simple>
</camel:when>

或者调用字符串的equals方法:

<camel:simple><![CDATA[${in.body}.equals('{"status":"OK"}')]]></camel:simple>

方案2:在XML属性中转义双引号(适合把表达式写在simple属性里)

如果习惯把表达式直接写在<camel:when>的simple属性中,需要把JSON里的双引号转义成XML实体&quot;:

<camel:choice>
    <camel:when simple="${in.body} startsWith '{&quot;status&quot;:&quot;OK&quot;}'">
        <!-- 匹配逻辑 -->
    </camel:when>
</camel:choice>

方案3:直接访问JSON字段(更健壮的方式)

如果你的消息体已经被Camel转换成了JSON对象(比如通过jackson或gson组件自动反序列化成Map或POJO),完全不用纠结字符串匹配,直接访问status字段更可靠,还能避免JSON格式差异(比如空格、换行)导致的匹配失败:

<camel:choice>
    <camel:when simple="${in.body.status} == 'OK'">
        <!-- 处理status为OK的情况 -->
    </camel:when>
</camel:choice>

如果消息还是原始JSON字符串,可以先通过jsonpath表达式来提取字段:

<camel:when>
    <camel:jsonpath>$.status == 'OK'</camel:jsonpath>
</camel:when>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:42:21