Search code examples
jsonjacksonfreemarker

Evaluate JSon with null value using Freemarker


When dealing with a JSon that some values are null Freemarker give an error in ?eval.

with mapper.setSerializationInclusion(Inclusion.NON_NULL) i can avoid this but i miss this information on the generated JSon.

There's a way to achieve the evaluation with this null values?

<#assign test = "{\"foo\":\"bar\"}">
<#assign m = test?eval>
${m.foo}  <#-- prints: bar -->

Fail in eval

<#assign test = "{\"foo\":null}">
<#assign m = test?eval> <#-- fail in eval -->
${m.foo}  

Solution

  • Update: FreeMarker 2.3.31 added ?eval_json. It can parse null, and can't call methods (which is a possible security issue with ?eval).

    Unfortunately (or... infuriatingly), FTL doesn't know the concept of null (although this might will change with 2.4). So even if you manage to create a Map from that JSON where the foo key exists but the associated value is null (like you create a such Map in Java), ${m.foo} will still fail. Surely you can write ${m.foo!'null'}, but that will print null even if there's no foo key at all. So maybe it's better if you provide a default value for the null-s during the JSON evaluation:

    <#function parseJSON json>
      <#local null = 'null'> <#-- null is not a keyword in FTL -->
      <#return json?eval>
    </#function>
    
    ${parseJSON("{\"foo\":null}").foo}  <#-- prints null -->
    

    Now, however, you can't tell the difference between "null" and null. If that's a problem, you could chose some odd default, like '@@@null' or even use a macro as indicator value and then use ?is_macro to test if the value was null (that hack is useful as JSON evaluation can't produce macros)...