app因为是依赖于后台的,后台说什么就是什么(本来字段应该移动端给定),所以当后台定死了一个接口文档后都直接丢给我们不会与我们讨论解析如何复杂。因此作为强大的客户端开发,要自己去适配解析了。
这里以轻松保价格列表数据为例观察下面json
{
"code": 0,
"message": "success",
"data": {"title": "鸿福e生百万医疗保障计划","insurance_uuid": "bd3791e5-c66c-4702-aa67-7eb44da84c3f","price_list": {"01": {"30day-4year": [{"coverage": 300000000,"pay_amount": 70500,"month_amount": 5900}],
"5year-10year": [{"coverage": 300000000,"pay_amount": 21600,"month_amount": 1850}],}}},
"next": ""
}
{
"code": 0,
"message": "success",
"data": {"title": "鸿福e生百万医疗保障计划","insurance_uuid": "bd3791e5-c66c-4702-aa67-7eb44da84c3f","price_list": {"02": {"30day-4year": [{"coverage": 300000000,"pay_amount": 70500,"month_amount": 5900}],
"5year-10year": [{"coverage": 300000000,"pay_amount": 21600,"month_amount": 1850}],}}},
"next": ""
}
{
"code": 0,
"message": "success",
"data": {"title": "鸿福e生百万医疗保障计划","insurance_uuid": "bd3791e5-c66c-4702-aa67-7eb44da84c3f","price_list": {"man": {"30day-4year": [{"coverage": 300000000,"pay_amount": 70500,"month_amount": 5900}],
"5year-10year": [{"coverage": 300000000,"pay_amount": 21600,"month_amount": 1850}],}}},
"next": ""
}
{
"code": 0,
"message": "success",
"data": {"title": "鸿福e生百万医疗保障计划","insurance_uuid": "bd3791e5-c66c-4702-aa67-7eb44da84c3f","price_list": {"30day-4year": [{"coverage": 300000000,"pay_amount": 70500,"month_amount": 5900}],
"5year-10year": [{"coverage": 300000000,"pay_amount": 21600,"month_amount": 1850}],}},
"next": ""
}
可以发现data里面数据格式不固定,外层和里层都不固定,猛一看到是不是很懵逼,网上所说千篇一律。花了点时间研究了下,再次记录下心得。
解决思路所知分为两种:
1:原生解析jsonobject
思路如下:根据jsonobject.keys方法拿到key的集合。然后遍历这个集合一层层解析就行了
2:如果用的数据解析是第三方比如:gson
因为数据格式不固定,所以我想着在module中都用map接,然后value都用object接,这样第一步数据解析算是完成了(Map<String, Object> priceList)
接下来在数据请求完成后转成自己需要的格式:
Map map = homePriceListBean.priceList;
先拿到map然后根据key拿到对应的object然后把object转成json(new Gson().toJson(map.get(securityValue)))
再把json转成自己需要的格式就可以了:
两层数据:
Map> priceDetailBeanMap = new Gson().fromJson(json,
new TypeToken>>() {
}.getType());
一层数据:
List priceDetailBeanMap =new Gson().fromJson(json,
new TypeToken>() {
}.getType());