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

Freemarker模板减少空检查及JSON中addressId提取问题

Extract addressId from nested JSON in FreeMarker with minimal null checks

Got it, let's tackle this problem of extracting the addressId from your nested JSON response while cutting down on those tedious null checks in FreeMarker. The good news is FreeMarker has built-in syntax that lets you avoid writing endless <#if> blocks for every nested property.

Simplest Solution: Use the Default Value Operator (!)

The ! operator is your best friend here. It handles null/non-existent properties along the entire access chain, returning a default value you specify instead of throwing an error. Here's how you can use it for your JSON structure:

${getKycBusinessDetailsResponse.ADDRESS.fieldDataResponse.dataValue.addressId!''}
  • If every property in the chain exists, this will output the addressId value (2BH6RKV6KLU4OAFIQGOEG12IX7FW7W7I6A2H6I7W7WF7XILPXTQ2EIA2OX4BY72H in your sample).
  • If any property in the chain is missing or null, it will output an empty string instead of breaking the template.

You can also customize the default value if you want a more informative fallback:

${getKycBusinessDetailsResponse.ADDRESS.fieldDataResponse.dataValue.addressId!'Address ID not available'}

Alternative: Conditional Check with ?has_content (For Explicit Control)

If you prefer to show different content based on whether the addressId exists (instead of just a default value), you can use the ?has_content test to simplify the conditional logic (no need for separate checks on every nested level):

<#if getKycBusinessDetailsResponse.ADDRESS.fieldDataResponse.dataValue?has_content>
    Address ID: ${getKycBusinessDetailsResponse.ADDRESS.fieldDataResponse.dataValue.addressId}
<#else>
    No valid address ID found
</#if>

?has_content returns true only if the target object exists and isn't empty, so this checks the entire chain up to dataValue in one go.

Why This Works

FreeMarker's property access syntax (obj.property) automatically handles missing properties by returning a "missing" value, and the ! operator catches that missing value to return your default. This eliminates the need to write <#if> checks for every single nested property in the chain.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:02:05