Using Gson to parse complex JSON data

Source: Internet
Author: User

Gson parsing of complex JSON data

Recently in the company to do a live APK project, mainly by parsing the network server JSON data, and then download the channel address and then call the Android player to play, Originally intended to use the common JSON parsing method, Jsonobject and Jsonarray, which is useful for parsing the JSON data of small data, but when parsing JSON data is more complex, this method seems to be more difficult and more troublesome, If you are interested, there are a lot of examples on the Internet to see the Internet.

Here I will introduce another way to parse JSON data is through Gson parsing, for parsing the simpler JSON data I will not introduce a more complex JSON data, such as the following we want to parse a JSON data:

String json = {"A": "+", "B": [{"B1": "B_value1", "B2": "B_value2"}, {"B1": "B_value1", "B2": "B_value2"}], "C": {"C1": "C_ Value1 "," C2 ":" C_value2 "}}

If the use of Jsonobject and Jsonarray with the use can be resolved but it is more difficult to parse, if the use of Gson parsing is relatively simple, first we need to define a serialized bean, which is used in the form of internal classes, it is easier to see more clearly

First we need to define a serialized bean, which, in the form of an inner class, will look clearer:

 Public classJsonbean { PublicString A;  PublicList<b>b;  Publicc C;  Public Static classB { PublicString B1;  PublicString B2; }              Public Static classC { PublicString C1;  PublicString C2; } }

Many times people do not know how this bean is defined, which should be noted in several points:

    • The inner nested class must be static, or the parsing will go wrong;
    • The property name inside the class must be identical to the key inside the JSON field;
    • The inner nested part is a List, so it is defined as public list<b> B, and only nested with {} is defined as public C c.

Specific people against the JSON string to see the understanding, do not understand that we can communicate with each other, I am also a novice developer!

Newnew typetoken<jsonbean>= Gson.fromjson (JSON, type);</span>

Then want to take the data is very simple, directly in the jsonbean inside to take it!
If you need to parse the JSON nested a lot of layers, you can also define a nested many layers of internal classes of beans, you need to carefully control the JSON field to define OH.

Below I will explain the complex JSON data by Gson way with a specific Lezilai
1. The data that will be parsed is in the following format

{    "Error": 0,    "Status": "Success",    "Date": "2014-05-10",    "Results":[        {            "CurrentCity": "Nanjing",            "Weather_data":[                {                    "Date": "Saturday (Today, Live: 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 Level 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": "Showers Turn cloudy",                    "Wind": "Northwest Wind Level 4-5",                    "Temperature": "21 ~ 14 ℃"                }            ]        }    ]}

2. Some of the following JavaBean data must be defined
Status.java

 Public classStatus {PrivateString error; PrivateString status; PrivateString date; PrivateList<results>results;  PublicString GetError () {returnerror; }         Public voidSetError (String error) { This. Error =error; }                 PublicString GetStatus () {returnstatus; }         Public voidsetStatus (String status) { This. Status =status; }         PublicString getDate () {returndate; }         Public voidsetDate (String date) { This. Date =date; }         PublicList<results>GetResults () {returnresults; }         Public voidSetResults (list<results>results) {             This. Results =results; } @Override PublicString toString () {return"Status [error=" + Error + ", status=" +Status+ ", date=" + Date + ", results=" + results + "]"; }

Results.java

 Public classResults {PrivateString currentcity; PrivateList<weather>Weather_data;  PublicString getcurrentcity () {returncurrentcity; }     Public voidsetcurrentcity (String currentcity) { This. currentcity =currentcity; }     PublicList<weather>Getweather_data () {returnWeather_data; }     Public voidSetweather_data (list<weather>weather_data) {         This. Weather_data =Weather_data; } @Override PublicString toString () {return"Results [currentcity=" + currentcity + ", weather_data=" + Weather_data + "]"; }

Weather.java

 Public classWeather {PrivateString date; PrivateString Daypictureurl; PrivateString Nightpictureurl; PrivateString Weather; PrivateString Wind; PrivateString temperature;  PublicString getDate () {returndate; }                 Public voidsetDate (String date) { This. Date =date; }                 PublicString Getdaypictureurl () {returnDaypictureurl; }                 Public voidSetdaypictureurl (String daypictureurl) { This. Daypictureurl =Daypictureurl; }                 PublicString Getnightpictureurl () {returnNightpictureurl; }                 Public voidSetnightpictureurl (String nightpictureurl) { This. Nightpictureurl =Nightpictureurl; }                 PublicString GetWeather () {returnweather; }                 Public voidSetweather (String weather) { This. Weather =weather; }                 PublicString Getwind () {returnWind ; }                 Public voidSetwind (String wind) { This. Wind =Wind ; }                 PublicString gettemperature () {returntemperature; }                 Public voidsettemperature (String temperature) { This. Temperature =temperature; } @Override PublicString toString () {return"Weather [date=" + Date + ", daypictureurl=" + Daypictureurl + ", nightpictureurl=" + Nightpictureurl + ", weather=" +Weather+ ", wind=" + Wind + ", temperature=" +Temperature+ "]"; }               

Then the specific JavaBean definition will parse the data, the following is my analytical data class

 Public classMainactivityextendsActivity {PrivateButton Tojson;        Requestqueue Mqueue;        Stringrequest stringrequest;    Gson Gson;    String str; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Tojson=(Button) Findviewbyid (R.id.tojson); Gson=NewGson (); Mqueue= Volley.newrequestqueue (mainactivity. This); //Http://10.19.20.12/upgrade/test.txtis the JSON data used by the testStringrequest =NewStringrequest ("Http://10.19.20.12/upgrade/test.txt",                NewResponse.listener<string>() {@Override Public voidOnresponse (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); }                },                 NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {LOG.E ("TAG", Error.getmessage (), error);          }                }); Tojson.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {mqueue.add (stringrequest);         }        }); }     }

The above requestqueue is the use of Open Source network library Volley, if you are not familiar with the use of the library can refer to http://blog.csdn.net/guolin_blog/article/details/ 17482095, the author of the volley library to explain the use of very detailed and in-depth
We can read it carefully.

Using Gson to parse complex JSON data

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.