java - 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.
解决方案
如果服务器向您发送 null ,您可以使用 Int 来存储该值,否则解析将不会成功;另一方面,如果您需要除 null 以外的其他值作为默认值,您可以覆盖您的 set 或 get 方法;set to if is null 将值设置为零或 get 如果值为 null 返回 0。
希望它有助于调试您的问题,如果服务器向您发送多个值,如字符串、布尔值等。您应该讨论哪个值是您需要的值。
推荐阅读
- javascript - setFilesToUpload 操作对我不起作用
- python - 来自两个输入数据集的多输出回归
- javascript - 如何在变量中调用函数?
- java - Spring MVC - 接收列表的 Rest 端点可能会接收单个对象
- python - 致命的python错误:Py_Initialize:无法加载文件系统编解码器
- excel-formula - 根据开始日期和结束日期计算动态列值
- xpath - 如何获取网页DOM的所有DOM层次结构
- mfc - SetFocus 和 KillFocus
- xbrl - 扩展 XBRL 表示网络
- android - 检测内存不足的最佳方法是什么?