Gson 解析容错框架,愿从此再无 Json 解析报错
dependencies { // Gson 解析容错:https://github.com/getActivity/GsonFactory implementation 'com.hjq.gson:factory:3.0' // Json 解析框架:https://github.com/google/gson implementation 'com.google.code.gson:gson:2.8.0' }
// 获取单例的 Gson 对象(已处理容错) Gson gson = GsonFactory.getSingletonGson();// 创建一个 Gson 构建器(已处理容错) GsonBuilder gsonBuilder = GsonFactory.createGsonBuilder();
目前支持容错的数据类型有:
JsonObject(Bean 对象本身)
JsonArray(数组或集合)
String(字符串)
boolean / Boolean(布尔值)
int / Integer(整数,属于数值类)
long /Long(长整数,属于数值类)
float / Float(单精度浮点数,属于数值类)
double / Double(双精度浮点数,属于数值类)
BigDecimal(精度更高的浮点数,属于数值类)
基本涵盖 99.99% 的开发场景,可以运行 Demo 中的单元测试用例来查看效果:
| 数据类型 | 容错的范围 | 数据示例 | | :----: | :------: | :-----: | | object | array、字符串、布尔值、数值 |
[]、
""、
false、
0| | array | object、字符串、布尔值、数值 |
{}、
""、
false、
0| | 字符串 | object、array、布尔值、数值 |
{}、
[]、
false、
0| | 布尔值 | object、array、字符串、数值 |
{}、
[]、
""、
0| | 数值 | object、array、字符串、布尔值 |
{}、
[]、
""、
false|
大家可能觉得 Gson 解析容错没什么,那是因为我们对 Gson 解析失败的场景没有了解过:
JsonObject,没数据返回
[],Gson 会直接抛出异常
整数,但是后台返回
浮点数,Gson 会直接抛出异常
布尔值,但是后台返回的是
0或者
1,Gson 会直接抛出异常
以上情况框架已经做了容错处理,具体处理规则如下:
跳过解析
取整
非 0 的数值则处理为 true,否则为 false
我觉得非常有必要,因为后台返回的数据结构是什么样我们把控不了,但是有一点是肯定的,我们都不希望它崩,因为一个接口的失败导致整个 App 崩溃退出实属不值得,但是 Gson 很敏感,动不动就崩。
如果你们的后台用的是 PHP,那我十分推荐你使用这个框架,因为 PHP 返回的数据结构真的很乱,经历过的人都懂,说多了都是泪。
如果你们的后台用的是 Java,那么可以根据实际情况而定,例如我现在的公司用的就是 Java 后台,但是 Bugly 有上报一个关于 Gson 解析的 Crash,所以说后台的嘴骗人的鬼,宁可相信鬼也不要相信后台那张嘴。
安卓技术中台:AndroidProject
网络框架:EasyHttp
吐司框架:ToastUtils
权限框架:XXPermissions
标题栏框架:TitleBar
悬浮窗框架:XToast
国际化框架:MultiLanguages
日志框架:Logcat
Copyright 2020 Huang JinQunLicensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.