首页 > 解决方案 > Android. Setting default value for invalid json field

问题描述

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.

标签: javaandroidjsonretrofit2converters

解决方案


如果服务器向您发送 null ,您可以使用 Int 来存储该值,否则解析将不会成功;另一方面,如果您需要除 null 以外的其他值作为默认值,您可以覆盖您的 set 或 get 方法;set to if is null 将值设置为零或 get 如果值为 null 返回 0。

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


推荐阅读