Android。为无效的 JSON 字段设置默认值

huangapple 未分类评论54阅读模式
标题翻译

Android. Setting default value for invalid json field

问题

我正在使用 Retrofit 和 JSON 转换器。我创建了一个包含一些字段的 POJO。其中一个字段应该是 int 类型,但如果服务器发送的不是 int 类型,我需要在这个字段中写入默认值,比如 2。现在,如果服务器发送的不是 int 类型,我在请求中会收到异常(JSON 格式错误异常),因为在 POJO 中该字段被声明为 int 类型。是否有可能在这个字段中写入默认值,如果服务器发送的不是 int 类型。

英文翻译

I am using retrofit and json converter. I create POJO which contains some fields. One of these fields should be int, but if the server sends something else instead of int, I need to write the default value in this field, for example 2. Now if the server sends something other than int, I get an exception (json malformed exception) in my request, since in the POJO the field is declared as int. Is it possible to write a default value in this field if the server sends something other than int.

答案1

得分: 0

如果服务器发送给您null,您可以使用Int来存储该值,否则解析将不会成功。另一方面,如果您需要一个与null不同的默认值,您可以覆盖您的设置或获取方法;如果为null,则将值设置为零,或者如果值为null,则返回0。

希望它能帮助您调试问题,如果服务器发送给您多个值,比如字符串、布尔值等等。您应该讨论您所需要的值是哪一个。

英文翻译

in case the server is sending you null you can use Int to store the value, otherwise the parsing won´t be successful; on the other hand if you require a different value other than null as a default you can override your set or get method; set to if is null set the value to zero or get if the value is null return 0.

Hope it helps to debug your problem, if the server is sending you multiple values like strings, booleans, etc. You should discuss which value is the one that you need.

huangapple
  • 本文由 发表于 2020年3月17日 02:42:04
  • 转载请务必保留本文链接:https://java.coder-hub.com/60711572.html
匿名

发表评论

匿名网友

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

确定