使用Freemarker评估带有null值的JSon

Rub*_*oso 3 json freemarker jackson

在处理JSon时,某些值为null Freemarker在?eval中给出错误.

mapper.setSerializationInclusion(Inclusion.NON_NULL)我能避免这一点,但我错过了产生JSON此信息.

有一种方法可以用这个空值来实现评估吗?

<#assign test = "{\"foo\":\"bar\"}">
<#assign m = test?eval>
${m.foo}  <#-- prints: bar -->
Run Code Online (Sandbox Code Playgroud)

评估失败

<#assign test = "{\"foo\":null}">
<#assign m = test?eval> <#-- fail in eval -->
${m.foo}  
Run Code Online (Sandbox Code Playgroud)

dde*_*any 6

不幸的是(或......令人愤怒),FTL不知道这个概念null(尽管这可能会随着2.4而改变).因此,即使您设法创建一个存在密钥的MapJSON,foo但关联的值null(就像您Map在Java中创建一样),${m.foo}仍然会失败.当然你可以写${m.foo!'null'},但null即使根本没有foo钥匙也会打印出来.因此,如果在JSON评估期间null-s 提供默认值,可能会更好:

<#function parseJSON json>
  <#local null = 'null'> <#-- null is not a keyword in FTL -->
  <#return json?eval>
</#function>

${parseJSON("{\"foo\":null}").foo}  <#-- prints null -->
Run Code Online (Sandbox Code Playgroud)

不过,现在你不能告诉之间的区别"null"null.如果这是一个问题,你可以选择一些奇怪的默认值,'@@@null'甚至使用一个宏作为指标值然后?is_macro用来测试该值是否null(该黑客是有用的,因为JSON评估不能产生宏)...