博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Gson解析JSON数据中动态未知字段key的方法
阅读量:6303 次
发布时间:2019-06-22

本文共 5159 字,大约阅读时间需要 17 分钟。

转载自: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
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
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
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的效率更高。

你可能感兴趣的文章
Hadoop日记Day1---Hadoop介绍
查看>>
iOS 学习资料汇总
查看>>
centos7 yum安装jdk
查看>>
Bluedroid与BluZ,蓝牙测试方法的变动(基于bludroid和BlueZ的对比)
查看>>
接口和抽象类有什么区别
查看>>
Linux 下添加用户,修改权限
查看>>
请问view controller scene,该如何删除
查看>>
bootstrap新闻模块样式模板
查看>>
zzzzw_在线考试系统①准备篇
查看>>
App Store 审核被拒的23个理由
查看>>
剑指offer第二版-1.赋值运算符函数
查看>>
javascript 对象
查看>>
Android学习笔记——文件路径(/mnt/sdcard/...)、Uri(content://media/external/...)学习
查看>>
Echart:前端很好的数据图表展现工具+demo
查看>>
CATransform3D iOS动画特效详解
查看>>
Linux VNC黑屏(转)
查看>>
Java反射简介
查看>>
react脚手架应用以及iview安装
查看>>
shell学习之用户管理和文件属性
查看>>
day8--socket网络编程进阶
查看>>