转载自:https://blog.csdn.net/jdsjlzx/article/details/76785239 有时在解析json数据中的字段key是动态可变的时候,由于Gson是使用静态注解的方式来设置实体对象的,因此我们很难直接对返回的类型来判断。但Gson在解析过程中如果不知道解析的字段,就会将所有变量存储在一个Map中,我们只要实例化这个map就能动态地取出key和value了。 先给出一段jsondata,这是天气预报的数据,其中day_20151002这种key是随日期而变化的,在实体类中就不能当做静态变量来处理,我们就通过map来取出其映射对象。

{"resultcode": "200","reason": "successed!","result": {"sk": {"temp": "24","wind_direction": "东北风","wind_strength": "2级","humidity": "28%","time": "17:38"},"today": {"temperature": "15℃~26℃","weather": "多云转晴","wind": "东北风微风","week": "星期日","city": "桂林","date_y": "2015年10月11日","dressing_index": "舒适","dressing_advice": "建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。","uv_index": "弱","comfort_index": "","wash_index": "较适宜","travel_index": "较适宜","exercise_index": "较适宜","drying_index": ""},"future": {"day_20151011": {"temperature": "15℃~26℃","weather": "多云转晴","wind": "东北风微风","week": "星期日","date": "20151011"},"day_20151012": {"temperature": "16℃~27℃","weather": "晴转多云","wind": "微风","week": "星期一","date": "20151012"},"day_20151013": {"temperature": "16℃~26℃","weather": "多云转晴",,"wind": "微风","week": "星期二","date": "20151013"},"day_20151014": {"temperature": "17℃~27℃","weather": "晴","wind": "北风微风","week": "星期三","date": "20151014"},"day_20151015": {"temperature": "17℃~28℃","weather": "晴","wind": "北风微风","week": "星期四","date": "20151015"},"day_20151016": {"temperature": "17℃~30℃","weather": "晴","wind": "北风微风","week": "星期五","date": "20151016"},"day_20151017": {"temperature": "17℃~30℃","weather": "晴","wind": "北风微风","week": "星期六","date": "20151017"}}},"error_code": 0
}
复制代码

相关的实体类如下:

public class FutureDay {private String temperature;private String weather;private String wind;private String week;private String date;
}public class Result {private Sk sk;private Today today;private Map<String,FutureDay> future;
}
public class Sk {private String temp;private String wind_direction;private String wind_strength;private String humidity;private String time;
}
public class Today {private String temperature;private String weather;private String week;private String city;private String date_y;private String dressing_index;private String dressing_advice;private String uv_index;private String comfort_index;private String wash_index;private String travel_index;private String exercise_index;private String drying_index;
}
public class Response {private String resultcode;private String reason;private String error_code;private Result result;
}
复制代码

具体解析过程如下代码所示:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Map;
import weather.*;
import com.google.gson.Gson;public class GsonParseDynamicKey {public static  void main( String args []){String jsondata = readJsonFile();//从文件中读取出json字符串,并打印出来Gson gson = new Gson();System.out.println("Start Gson parse jsondata");   Response response = gson.fromJson(jsondata, Response.class);        System.out.println(response.toString());System.out.println(response.getResult().getSk().toString());System.out.println(response.getResult().getToday().toString());Map<String, FutureDay> future = response.getResult().getFuture(); //对动态的key,来创建map,间接从中取出实体类futrue。System.out.println("Keyset method");                     //这里取出value的方法有两种keySet() entrySet().都给出了遍历的方法for (String key:future.keySet()){                        //遍历取出key,再遍历map取出value。System.out.println("key:"+key); System.out.println(future.get(key).toString());}System.out.println("Entryset method");for (Map.Entry<String,FutureDay> pair:future.entrySet()){//遍历取出键值对,调用getkey(),getvalue()取出key和value。System.out.println("key:"+pair.getKey());System.out.println(pair.getValue().toString());}
}
复制代码

这里顺便一提遍历Map的两种方法keySet(),entrySet()的差别。 keySet()方法返回的是key的集合set,entrySet()返回的是键值对的集合set。虽然两者从set遍历取出元素的方法是一样的,但是根据这个元素取出value的效率有些不同。前者取出的元素是key,还要去原map中遍历取出value。 后者取出的元素是键值对,直接调用getkey(),getvalue()方法就能快速取出key和value。显然在map中存在大量键值对时,使用entrySet()来取出value的效率更高。

Gson解析JSON数据中动态未知字段key的方法相关推荐

  1. gson解析php,php,android_关于 Gson 解析JSON数据。。。,php,android - phpStudy

    关于 Gson 解析JSON数据... 1.首先,我是从服务器端传回来的JSON数据如下: {"info":"succeed","user_id&qu ...

  2. JSONObject 和 GSON 解析 JSON 数据详解(转)

    转载:http://www.jianshu.com/p/f99de3ec0636 点此进入:从零快速构建APP系列目录导图 点此进入:UI编程系列目录导图 点此进入:四大组件系列目录导图 点此进入:数 ...

  3. Android利用Gson解析Json数据

    其实,要创建和解析JSON数据,也可以使用GSON来完成.GSON是Google提供的用来在Java对象和JSON数据之间进行映射的Java类库.使用GSON,可以很容易的将一串JSON数据转换为一个 ...

  4. Okhttp源码分析以及Google Gson解析json数据实例

    Okhttp Github的Okhttp OkHttp是一个高效的HTTP客户端,它有以下默认特性: 支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接 透明的GZIP压缩减少响 ...

  5. Android中Gson解析json数据使用@SerializedName注解

    @SerializedName 此注解作用在属性上,表明这个属性在序列化成Json的时候,需要将名字序列化成注解的value属性指定的值. 我们有一段json数据如下: { "id" ...

  6. 用Google提供的Gson解析JSON数据

    2019独角兽企业重金招聘Python工程师标准>>> 解析Json也就是触类旁通的一个过程,废话不说,比如我们要解析一个下面这种的Json,我们用的是Google的一个开源Gson ...

  7. Gson解析json数据 亲自测试可用

    2019独角兽企业重金招聘Python工程师标准>>> {     HosPitalInventoryInfo: {         HosPitalInventorylist: [ ...

  8. 通过Gson解析Json数据

    具体见下方链接 https://www.cnblogs.com/tianzhijiexian/p/4246497.html https://www.pianshen.com/article/46291 ...

  9. Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)

    JSON介绍: JSON:JavaScript对象表示法 JSON是存储和交换文本信息的语法. 特点: JSON是轻量级的文本数据交换格式 JSON独立于语言和平台 JSON具有自我描述性,更易理解 ...

最新文章

  1. 在CentOS 6.6 64bit上安装Python 3.5.0
  2. 用Zabbix部署onalert云告警平台
  3. git 挽救忘记提交到哪个分支的代码
  4. C#大型医院管理系统源码
  5. git源码安装后报错:bash: /usr/bin/git: No such file or directory
  6. 基于vue.js 编写的简单的文件管理器的demo
  7. 好用的网页在线客服工具
  8. SpringBoot + uni-app开发企业级图书商城系统
  9. 【主板上各种接口和附属部件科普】
  10. iOS-Cannot find interface declaration for 'XX', superclass of 'XX'
  11. 海康威视摄像头web二次开发(angular)
  12. 圣墟 第一百二十九章 异类直播
  13. 香港服务器机房TKO
  14. “因为无法从捐赠中抽成,谷歌把我的开源 App 下架了!”
  15. 怎样选数据分析培训机构,靠谱的数据分析培训机构有哪些
  16. 【Jetson-Nano】SD卡重新格式化
  17. Abbkine通用型免疫(共)沉淀试剂盒解决方案
  18. 如何将监控画面嵌入微信公众号进行直播
  19. 数据科学与大数据技术的就业前景
  20. echart制作出中国地图飞线图

热门文章

  1. 【Android】java.lang.AssertionError use looper thread, must call Looper.prepare() first!异常分析
  2. 用python画猪_用python画小猪票佩奇
  3. 解析SharedPreferences
  4. 你不知道的CSS单位
  5. Lua------------------unity与lua的热更新
  6. Python【Python基础】
  7. Nginx负载均衡:分布式/热备Web Server的搭建
  8. 第一次经历黑客攻击服务器系统
  9. CSS盒子模型之CSS3可伸缩框属性(Flexible Box)
  10. android 绘图之Canvas,Paint类