JSON转POJO字段的空值检查

huangapple go评论82阅读模式
英文:

JSON to POJO null check for fields

问题

我有一个非常大且复杂的JSON,我正在将其映射到一个简单的POJO(只包含所需的字段)。在Groovy中,JSON被解释为Map。

MyObject build(Map<String, Object> payload){

    ...
    o.name = payload.a.b.name
    o.gender = payload.c.d.e.gender

    return o
}

这些字段是可选的,如果不存在会抛出NullPointerException。如何映射为空字符串"",而不是为每行都添加try-catch?可能很直接,但我想不出如何做。

英文:

I have a very large complex JSON and I'm mapping this to a simple POJO (with only the required fields). In groovy JSON is interpreted as Map.

MyObject build(Map&lt;String, Object&gt; payload){

...
    o.name = payload.a.b.name
    o.gender = payload.c.d.e.gender

return o
}

The fields are optional and throws NullPointerException when not present. How to map to "" without putting try-catch for each line? My be straight forward but can't figure out how.

答案1

得分: 0

安全导航操作符和Elvis操作符结合起来使用。

如果在遍历payload时出现异常:

o.gender = payload.c.d.e.gender

将其更改为:

o.gender = payload?.c?.d?.e?.gender ?: Gender.UNSET

(如果允许null,则可以省略?:...部分)

英文:

You would combine the safe navigation operator and the elvis operator.

If this throws while walking down the payload:

o.gender = payload.c.d.e.gender

Change it to:

o.gender = payload?.c?.d?.e?.gender ?: Gender.UNSET

(or if a null is fine, then leave out the ?:... part)

huangapple
  • 本文由 发表于 2020年8月4日 11:21:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63239763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定