英文:
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<String, Object> 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论