减少自由标记模板中的空检查

时间:2018-03-29 20:02:52

标签: freemarker

我有json:

{"getKycBusinessDetailsResponse": 
  {"ADDRESS": 
    {"fieldDataResponse":
      {  "dataValue": 
          {"__type": "com.amazon.skies#AddressData", 
           "addressId": "2BH6RKV6KLU4OAFIQGOEG12IX7FW7W7I6A2H6I7W7WF7XILPXTQ2EIA2OX4BY72H"},
         "isEditable": false, 
       "isMandatory": false, 
       "isUpdateRequired": false}, 
     "fieldDocumentsResponse": 
      {"documentValue": 
        {}, 
       "isMandatory": false, 
       "isUpdateRequired": false}
    }
  }
}

我想从上面的Json中提取addressId值,这就是我所做的:

<#if getKYCBusinessData??>
    <#assign getKYCBusinessData = (getKYCBusinessData)?eval>
    <#if getKYCBusinessData.getKycBusinessDetailsResponse?? && getKYCBusinessData.getKycBusinessDetailsResponse?has_content>
        <#assign businessDetails = getKYCBusinessData.getKycBusinessDetailsResponse>
        <#if businessDetails.ADDRESS?? && businessDetails.ADDRESS?has_content>
            <#assign ADDRESS = businessDetails.ADDRESS>
            <#if ADDRESS.fieldDataResponse?? && ADDRESS.fieldDataResponse?has_content>
                <#assign fieldDataResponse = ADDRESS.fieldDataResponse>
                <#if fieldDataResponse.dataValue?? && fieldDataResponse.dataValue?has_content>
                    <#assign dataValue = fieldDataResponse.dataValue>
                    <#if dataValue.addressId?? && dataValue.addressId?has_content>
                        <#assign addressId = dataValue.addressId>
                            {
                                "addressId" : "${addressId}"
                            }
                    </#if>
                </#if>
            </#if>
        </#if>
    </#if>
</#if>

正如您在此处可以看到提取地址ID一样,需要应用多个空检查。如何在这里减少空检查的数量?

1 个答案:

答案 0 :(得分:2)

关键是要了解(...)!构造,它同时构成[](以及""false,但我们不会如果由于缺少变量而失败,则利用那个内部的表达式。使解决方案仍然冗长的原因是,如果输出内部的东西退出,您只需要输出中的{ ... }。为了解决这个问题,我将结果视为0或1长的列表:

<#list ([ getKYCBusinessData.getKycBusinessDetailsResponse.ADDRESS
          .fieldDataResponse.dataValue.addressId ])! as it>
   {
      "addressId": "${it}"
   }
</#list>

另一种方法是#assign并执行#if,但是,它无法区分真正缺失的值与存在的值但是具有类似值{的值{1}}:

""