Freemarker模板减少空检查及JSON中addressId提取问题
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
addressIdvalue (2BH6RKV6KLU4OAFIQGOEG12IX7FW7W7I6A2H6I7W7WF7XILPXTQ2EIA2OX4BY72Hin 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

