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

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

  1. 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,这里采用内部类的形式,看起来会比较清晰一些:

  1. public class JsonBean {
  2. public String a;
  3. public List<B> b;
  4. public C c;
  5.  
  6. public static class B {
  7.  
  8. public String b1;
  9.  
  10. public String b2;
  11. }
  12.  
  13. public static class C {
  14. public String c1;
  15. public String c2;
  16. }
  17. }

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

  1. Gson gson = new Gson();
  2. java.lang.reflect.Type type = new TypeToken<JsonBean>() {}.getType();
  3. 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

  1. public class Status
  2. {
  3. private String error;
  4. private String status;
  5. private String date;
  6. private List<Results> results;
  7. public String getError()
  8. {
  9. return error;
  10. }
  11. public void setError(String error)
  12. {
  13. this.error = error;
  14. }
  15.  
  16. public String getStatus()
  17. {
  18. return status;
  19. }
  20. public void setStatus(String status)
  21. {
  22. this.status = status;
  23. }
  24. public String getDate()
  25. {
  26. return date;
  27. }
  28. public void setDate(String date)
  29. {
  30. this.date = date;
  31. }
  32. public List<Results> getResults()
  33. {
  34. return results;
  35. }
  36. public void setResults(List<Results> results)
  37. {
  38. this.results = results;
  39. }
  40. @Override
  41. public String toString()
  42. {
  43. return "Status [error=" + error + ", status=" + status
  44. + ", date=" + date + ", results=" + results + "]";
  45. }
  46. </span>

Results.java

  1. public class Results
  2. {
  3. private String currentCity;
  4. private List<Weather> weather_data;
  5. public String getCurrentCity()
  6. {
  7. return currentCity;
  8. }
  9. public void setCurrentCity(String currentCity)
  10. {
  11. this.currentCity = currentCity;
  12. }
  13. public List<Weather> getWeather_data()
  14. {
  15. return weather_data;
  16. }
  17. public void setWeather_data(List<Weather> weather_data)
  18. {
  19. this.weather_data = weather_data;
  20. }
  21. @Override
  22. public String toString()
  23. {
  24. return "Results [currentCity=" + currentCity + ", weather_data="
  25. + weather_data + "]";
  26. }

Weather.java

  1. public class Weather {
  2. private String date;
  3. private String dayPictureUrl;
  4. private String nightPictureUrl;
  5. private String weather;
  6. private String wind;
  7. private String temperature;
  8. public String getDate() {
  9. return date;
  10. }
  11. public void setDate(String date) {
  12. this.date = date;
  13. }
  14. public String getDayPictureUrl() {
  15. return dayPictureUrl;
  16. }
  17. public void setDayPictureUrl(String dayPictureUrl) {
  18. this.dayPictureUrl = dayPictureUrl;
  19. }
  20. public String getNightPictureUrl() {
  21. return nightPictureUrl;
  22. }
  23. public void setNightPictureUrl(String nightPictureUrl) {
  24. this.nightPictureUrl = nightPictureUrl;
  25. }
  26. public String getWeather() {
  27. return weather;
  28. }
  29. public void setWeather(String weather) {
  30. this.weather = weather;
  31. }
  32. public String getWind() {
  33. return wind;
  34. }
  35. public void setWind(String wind) {
  36. this.wind = wind;
  37. }
  38. public String getTemperature() {
  39. return temperature;
  40. }
  41. public void setTemperature(String temperature) {
  42. this.temperature = temperature;
  43. }
  44. @Override
  45. public String toString() {
  46. return "Weather [date=" + date + ", dayPictureUrl="
  47. + dayPictureUrl + ", nightPictureUrl="
  48. + nightPictureUrl + ", weather=" + weather
  49. + ", wind=" + wind + ", temperature=" + temperature
  50. + "]";
  51. }

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

  1. public class MainActivity extends Activity
  2. {
  3. private Button tojson;
  4. RequestQueue mQueue;
  5. StringRequest stringRequest;
  6. Gson gson;
  7. String str;
  8.  
  9. &nbsp; @Override
  10. protected void onCreate(Bundle savedInstanceState)
  11. {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_main);
  14.  
  15. tojson = (Button)findViewById(R.id.tojson);
  16. gson = new Gson();
  17.  
  18. mQueue = Volley.newRequestQueue(MainActivity.this);
  19. //http://10.19.20.12/upgrade/test.txt是测试使用的json数据
  20. stringRequest = new StringRequest("http://10.19.20.12/upgrade/test.txt",
  21. new Response.Listener<String>()
  22. {
  23. @Override
  24. public void onResponse(String response)
  25. {
  26. Log.d("TAG", response);
  27. System.out.println("response="+response);
  28. Status status = gson.fromJson(response, Status.class);
  29. System.out.println("status="+status);
  30. System.out.println("-------------------------------------");
  31. List<Results> result = status.getResults();
  32. System.out.println("result="+result);
  33.  
  34. }
  35. },
  36. new Response.ErrorListener()
  37. {
  38. @Override
  39. public void onErrorResponse(VolleyError error)
  40. {
  41. Log.e("TAG", error.getMessage(), error);
  42. }
  43.  
  44. });
  45.  
  46. tojson.setOnClickListener(new OnClickListener()
  47. {
  48. @Override
  49. public void onClick(View v)
  50. {
  51. mQueue.add(stringRequest);
  52. }
  53. });
  54. }
  55.  
  56. }

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

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

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

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

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

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

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

    http://stackoverflow.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. $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++】 解析与构建 Json 数据

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

随机推荐

  1. 网站SEO优化之添加Sitemap文件。

    Sitemap.xml 故名思意就是站点地图文件,可以指引Google spider 收录相应网页.正确地使用Google Sitemap,可以确保让Google spider 不遗漏网站内的任何页面 ...

  2. 欧几里得证明$\sqrt{2}$是无理数

    选自<费马大定理:一个困惑了世间智者358年的谜>,有少许改动. 原译者:薛密 \(\sqrt{2}\)是无理数,即不能写成一个分数.欧几里得以反证法证明此结论.第一步是假定相反的事实是真 ...

  3. RelativeLayout布局

    RelativeLayout用到的一些重要的属性: 第一类:属性值为true或falseandroid:layout_centerHrizontal 水平居中android:layout_center ...

  4. 如何自定义wordpress登录界面的Logo

    每次登录wp后台都会看到wordpress的logo,会不会有点烦呢?想不想换个新的.自己设定一个呢?那么如何自定义wordpress登录界面的Logo呢? 把代码复制到当前主题的 functions ...

  5. H5案例分享:html5重力感应事件

    html5重力感应事件 一.手机重力感应图形分析 1.设备围绕z轴的旋转角度为α,α角度的取值范围在[0,360). 设备在初始位置,与地球(XYZ)和身体(XYZ)某个位置对齐. 设备围绕z轴的旋转 ...

  6. Android应用中返回键的监听及处理

    MainActivity: package com.testnbackpressed;  import android.os.Bundle;  import android.view.KeyEvent ...

  7. jetbrick,新一代 Java 模板引擎,具有高性能和高扩展性

    新一代 Java 模板引擎,具有高性能和高扩展性. <!-- Jetbrick Template Engineer --> <dependency> <groupId&g ...

  8. Distinct Subsequences Leetcode

    Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...

  9. Android 创建内容提供器(ContentResolver)

    如果想实现跨程序共享数据的功能,官方推荐的方式就是使用内容提供器,可以通过新建一个类去继承 ContentResolver 的方式来创建一个自己的内容提供器. ContentProvider 类中有六 ...

  10. Codeforces 519 E. A and B and Lecture Rooms

    Description 询问一个树上与两点距离相等的点的个数. Sol 倍增求LCA. 一棵树上距离两点相等,要么就只有两点的中点,要么就是与中点相连的所有点. 有些结论很容易证明,如果距离是偶数,那 ...