Parsing Json nested data with Gson in Android Development

Source: Internet
Author: User

Parsing Json nested data with Gson in Android Development
Gson parses complex json data

Another method to parse json data is described here through Gson resolution. I will not introduce a complicated json data for parsing relatively simple json data, the following is a json data to be parsed:

[Java]
  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 }}

    If you use the combination of JsonObject and JsonArray, it can be parsed, but it is troublesome to parse it. If you use Gson for parsing, it is easier. First, we need to define a serialized Bean, the internal class is used here, which is easier to see.

    First, we need to define a serialized Bean. Here we use the internal class form, which looks clearer:

    [Java]
    1. Public class JsonBean {
    2. Public String;
    3. Public ListB;
    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. }


      Most of the time, you do not know how to define this Bean. Here, you need to pay attention to the following points:
      1. Internal Nested classes must be static, otherwise parsing will fail;
      2. the attribute names in the class must be exactly the same as the keys in the Json field;
      3. The part enclosed in [] is a List, which is defined as public List.B, and the nested {} is defined as public C c,
      You can check the Json string for details. If you do not understand, you can communicate with each other. I am also a beginner in development!

      [Java]View plaincopy
      1. Gson gson = new Gson ();
      2. Java. lang. reflect. Type type = new TypeToken () {}. GetType ();
      3. JsonBean jsonBean = gson. fromJson (json, type );

        Then it's easy to get the data, just retrieve it in jsonBean!
        If the Json to be parsed is nested in many layers, you can also define a Bean with many layers of internal classes. You need to carefully compare the Json fields to define the Bean.

        The following describes how to parse complex json data using a specific column in Gson mode.
        1. The data to be parsed is in the following format:

        {
        Error: 0,
        Status: success,
        Date: 2014-05-10,
        Results :[
        {
        CurrentCity: Nanjing,
        Weather_data :[
        {
        Date: Saturday (today, real-time: 19 ℃ ),
        DayPictureUrl: http://api.map.baidu.com/images/weather/day/dayu.png,
        NightPictureUrl: http://api.map.baidu.com/images/weather/night/dayu.png,
        Weather: heavy rain,
        Wind: southeast wind 5-6,
        Temperature: 18 ℃
        },
        {
        Date: Sunday,
        DayPictureUrl: http://api.map.baidu.com/images/weather/day/zhenyu.png,
        NightPictureUrl: http://api.map.baidu.com/images/weather/night/duoyun.png,
        Weather: Shower turns cloudy,
        Wind: northwest wind 4-5,
        Temperature: 21 ~ 14 ℃
        }
        ]
        }
        ]
        }
        2. You must define the following javaBean data.
        Status. java
        [Java]View plaincopy
        1. Public class Status
        2. {
        3. Private String error;
        4. Private String status;
        5. Private String date;
        6. Private List 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 GetResults ()
        33. {
        34. Return results;
        35. }
        36. Public void setResults (List 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. } Results. java
          [Java]View plaincopy
          1. Public class Results
          2. {
          3. Private String currentCity;
          4. Private List 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 GetWeather_data ()
          14. {
          15. Return weather_data;
          16. }
          17. Public void setWeather_data (List 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
            [Java]View plaincopy
            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. Maid = maid;
            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. }
            52. Then the specific javabean definition will parse the data. below is my parsing data class
              [Java]View plaincopy
              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. @ 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 is the json data used for testing.
              20. StringRequest = new StringRequest (http: // 10.19.20.12/upgrade/test.txt,
              21. New Response. Listener ()
              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 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.  
              57.  
              58. }
              59. The above RequestQueue is the use of the open-source network library Volley. If you are not familiar with the use of this library, refer
                You can read it carefully. Reprinted: http://blog.csdn.net/tkwxty/article/details/34474501

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.