Gson 解析复杂的 json 数据

Gson 解析复杂的 json 数据

解析 json 数据的方法是通过 Gson 解析,来一个比较复杂一点的 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);

    

       然后想拿数据就很简单啦,直接在 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.          }  
    
          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.  
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;  
    
  9.      @Override  
    
10.      protected void onCreate(Bundle savedInstanceState)   
    
11.      {  
    
12.          super.onCreate(savedInstanceState);  
    
13.          setContentView(R.layout.activity_main);  
    
          15.          tojson = (Button)findViewById(R.id.tojson);  
    
16.          gson = new Gson();  
    
  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);  
    
                          34.                      }  
    
35.                  },   
    
36.                  new Response.ErrorListener()   
    
37.                  {  
    
38.                      @Override  
    
39.                      public void onErrorResponse(VolleyError error)   
    
40.                      {  
    
41.                          Log.e("TAG", error.getMessage(), error);  
    
42.                      }  
    
  44.                  });  
    
    46.          tojson.setOnClickListener(new OnClickListener()   
    
47.          {         
    
48.              @Override  
    
49.              public void onClick(View v)   
    
50.              {  
    
51.                  mQueue.add(stringRequest);  
    
52.              }  
    
53.          });       
    
54.      }  
    
           58.  }  

其中上面的 RequestQueue 是开源网络库 Volley 的使用,如果你对该库的使用还不熟悉的话可以参考http://blog.csdn.net/guolin_blog/article/details/17482095,该作者对 Volley 库的使用讲解得非常的细致和深入

大家可以仔细的去拜读。

下面是解析示例:

public class MainActivity extends AppCompatActivity {

  

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

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Gson gson = new Gson();

        java.lang.reflect.Type type = new TypeToken<JsonBean>() {}.getType();

        JsonBean jsonBean = gson.fromJson(json, type);

  

        TextView a = (TextView)findViewById(R.id.hello);

        a.setText(jsonBean.toString());

  

    }

}


  
    展开阅读全文