Gson解析复杂的json数据

时间:2022-08-24 20:42:59

最近在给公司做一个直播APK的项目,主要就是通过解析网络服务器上的json数据,然后将频道地址下载下来再调用Android的播放器进行播放,原先本来打算使用普通的json解析方法即JsonObject和JsonArray的配合使用,这对于解析小数据的json数据还是比较实用,但是当解析json数据比较复杂的时候这种方法就显得比较吃力也比较麻烦了,如果大家感兴趣的话网上有大量的实例可以到网上去看看。

在这里我将介绍解析json数据的另外一种方法就是通过Gson解析,对于解析比较简单的json数据我就不介绍了来一个比较复杂一点的json数据,如下面我们要解析的一个json数据:

 String json = {"a":"100","b":[{"b1":"b_value1","b2":"b_value2"}, {"b1":"b_value1","b2":"b_value2"}],"c": {"c1":"c_value1","c2":"c_value2"}}

如果使用JsonObject和JsonArray的配合起来使用也是可以解析的但是解析起来就比较麻烦了,如果使用Gson解析就比较简单了,首先我们需要定义一个序列化的Bean,这里采用内部类的形式,这样比较容易看得清晰些

首先我们需要定义一个序列化的Bean,这里采用内部类的形式,看起来会比较清晰一些:

 public class JsonBean {
public String a;
public List<B> b;
public C c; public static class B { public String b1; public String b2;
} public static class C {
public String c1;
public String c2;
}
}

很多时候大家都是不知道这个Bean是该怎么定义,这里面需要注意几点:
             1、内部嵌套的类必须是static的,要不然解析会出错;
             2、类里面的属性名必须跟Json字段里面的Key是一模一样的;
             3、内部嵌套的用[]括起来的部分是一个List,所以定义为 public List<B> b,而只用{}嵌套的就定义为 public C c,
                  具体的大家对照Json字符串看看就明白了,不明白的我们可以互相交流,本人也是开发新手!

              Gson gson = new Gson();
java.lang.reflect.Type type = new TypeToken<JsonBean>() {}.getType();
JsonBean jsonBean = gson.fromJson(json, type);</span>

然后想拿数据就很简单啦,直接在jsonBean里面取就可以了!
       如果需要解析的Json嵌套了很多层,同样可以可以定义一个嵌套很多层内部类的Bean,需要细心的对照Json字段来定义哦。

下面我将以一个具体的列子来说明通过Gson方式解析复杂的json数据
1.将要解析的数据如下面的格式

{
    "error": 0,
    "status": "success",
    "date": "2014-05-10",
    "results": [
        {
            "currentCity": "南京",
            "weather_data": [
                {
                    "date": "周六(今天, 实时:19℃)",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/dayu.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/dayu.png",
                    "weather": "大雨",
                    "wind": "东南风5-6级",
                    "temperature": "18℃"
                },
                {
                    "date": "周日",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
                    "weather": "阵雨转多云",
                    "wind": "西北风4-5级",
                    "temperature": "21 ~ 14℃"
                }
            ]
        }
    ]
}
2.必须定义如下一些的javaBean数据
Status.java

 public class Status
{
private String error;
private String status;
private String date;
private List<Results> results;
public String getError()
{
return error;
}
public void setError(String error)
{
this.error = error;
} public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public List<Results> getResults()
{
return results;
}
public void setResults(List<Results> results)
{
this.results = results;
}
@Override
public String toString()
{
return "Status [error=" + error + ", status=" + status
+ ", date=" + date + ", results=" + results + "]";
}
</span>

Results.java

 public class Results
{
private String currentCity;
private List<Weather> weather_data;
public String getCurrentCity()
{
return currentCity;
}
public void setCurrentCity(String currentCity)
{
this.currentCity = currentCity;
}
public List<Weather> getWeather_data()
{
return weather_data;
}
public void setWeather_data(List<Weather> weather_data)
{
this.weather_data = weather_data;
}
@Override
public String toString()
{
return "Results [currentCity=" + currentCity + ", weather_data="
+ weather_data + "]";
}

Weather.java

 public class Weather {
private String date;
private String dayPictureUrl;
private String nightPictureUrl;
private String weather;
private String wind;
private String temperature;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDayPictureUrl() {
return dayPictureUrl;
}
public void setDayPictureUrl(String dayPictureUrl) {
this.dayPictureUrl = dayPictureUrl;
}
public String getNightPictureUrl() {
return nightPictureUrl;
}
public void setNightPictureUrl(String nightPictureUrl) {
this.nightPictureUrl = nightPictureUrl;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
@Override
public String toString() {
return "Weather [date=" + date + ", dayPictureUrl="
+ dayPictureUrl + ", nightPictureUrl="
+ nightPictureUrl + ", weather=" + weather
+ ", wind=" + wind + ", temperature=" + temperature
+ "]";
}

然后具体的javabean定义好了就将解析数据了,下面就是我的解析数据类

 public class MainActivity extends Activity
{
private Button tojson;
RequestQueue mQueue;
StringRequest stringRequest;
Gson gson;
String str; &nbsp; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); tojson = (Button)findViewById(R.id.tojson);
gson = new Gson(); mQueue = Volley.newRequestQueue(MainActivity.this);
//http://10.19.20.12/upgrade/test.txt是测试使用的json数据
stringRequest = new StringRequest("http://10.19.20.12/upgrade/test.txt",
new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
Log.d("TAG", response);
System.out.println("response="+response);
Status status = gson.fromJson(response, Status.class);
System.out.println("status="+status);
System.out.println("-------------------------------------");
List<Results> result = status.getResults();
System.out.println("result="+result); }
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Log.e("TAG", error.getMessage(), error);
} }); tojson.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mQueue.add(stringRequest);
}
});
} }

其中上面的RequestQueue是开源网络库Volley的使用,如果你对该库的使用还不熟悉的话可以参考前面的文章,其中对Volley的讲解也很详细了,相信各位朋友很快便能领悟出来。

Gson解析复杂的json数据的更多相关文章

  1. 使用Gson解析复杂的json数据

    Gson解析复杂的json数据 最近在给公司做一个直播APK的项目,主要就是通过解析网络服务器上的json数据,然后将频道地址下载下来再调用Android的播放器进行播放,原先本来打算使用普通的jso ...

  2. Gson解析第三方提供Json数据(天气预报,新闻等)

    之前都是自己写后台,自己的server提供数据给client. 近期在看第三方的数据接口,訪问其它站点提供的信息.比方.我们可能自己收集的数据相当有限.可是网上提供了非常多关于天气预报.新闻.星座运势 ...

  3. Gson 解析多层嵌套JSON数据

    http://*.com/questions/14139437/java-type-generic-as-argument-for-gson

  4. 【转】Jquery ajax方法解析返回的json数据

    转自http://blog.csdn.net/haiqiao_2010/article/details/12653555 最近在用jQuery的ajax方法传递接收json数据时发现一个问题,那就是返 ...

  5. hive 存储,解析,处理json数据

    hive 处理json数据总体来说有两个方向的路走 1.将json以字符串的方式整个入Hive表,然后通过使用UDF函数解析已经导入到hive中的数据,比如使用LATERAL VIEW json_tu ...

  6. Json1:使用gson解析、生成json

    Json解析: 1.json第三方解析包:json-lib.gson.jackson.fastjson等2.Google-gson只兼容jdk1.5版本以上:JSON-lib分别支持1.4和1.53. ...

  7. &dollar;Java-json系列(二):用JSONObject解析和处理json数据

    本文中主要介绍JSONObject处理json数据时候的一些常用场景和方法. (一)jar包下载 所需jar包打包下载百度网盘地址:https://pan.baidu.com/s/1c27Uyre ( ...

  8. 用JSONObject解析和处理json数据

    (一)jar包下载 所需jar包打包下载百度网盘地址:https://pan.baidu.com/s/1c27Uyre (二)常见场景及处理方法 1.解析简单的json字符串: 1 // 简单的jso ...

  9. 【UE4 C&plus;&plus;】 解析与构建 Json 数据

    准备条件 Json 格式 { "Players":[ { "Name": "Player1", "health": 20 ...

随机推荐

  1. SSRS 实用技巧 ---- 为表格添加展开&sol;折叠操作(明细报表)

    相信很多人都会遇到这样的需求:当表格按照某几个列分组时,需要为组添加展开和折叠的操作. 最初展现表格的时候只展现最外层分组,然后点击展开后可以查看分组内的明细情况. 先来一张效果图,然后再看具体如何实 ...

  2. input type&equals;&quot&semi;datetime-local&quot&semi; 时placeholder不显示

    一个坑,input的type="datetime-local" 时,电脑上会显示提示,如图 <input type="datetime-local" na ...

  3. Java基础知识笔记(四:多线程基础及生命周期)

    一.多线程基础 编写线程程序主要是构造线程类.构造线程类的方式主要有两种,一种是通过构造类java.lang.Thread的子类,另一种是通过构造方法实现接口java.lang.Runnable的类. ...

  4. 【点滴积累,厚积薄发】windows schedule task中&period;exe程序的路径问题等问题总结

    1.在发布ReportMgmt的Job时遇到一个路径问题,代码如下: doc.Load(@"Configuration\Business\business.config");   ...

  5. UVa 10300 - Ecological Premium

    https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=94&page=s ...

  6. LDAP查询过滤语法(MS)

    http://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters ...

  7. DButils实现查询和新增

             public static Adttendance DBSql(String data) throws SQLException {     String url = "j ...

  8. Ubuntu16&period;04 安装openjdk-7-jdk

    Ubuntu16.04 安装openjdk-7-jdk sudo apt-get install openjdk-7-jre 或者sudo apt-get install openjdk-7-jdk ...

  9. service structure flowchart with full stack functionality in a brife map

    More functionality will be added and running This diagram is just an easy chart for people to digest

  10. Extjs视频

    Extjs视频http://www.youku.com/playlist_show/id_19343298.html ExtJs视频教程(关东升) 智捷关东升老师ExtJs视频教程AJAX框架-Ext ...