Get up and develop the weather software for Android (iv)--use Gson to parse data

Source: Internet
Author: User

From the previous article in the past only 4, 5 days, we hurry to the hot strike continue to complete the series of weather software development. To undertake the contents of the previous chapter using volley to achieve network communication, returned to us is this string of JSON data {"Weatherinfo": {"City": "Hangzhou", "Cityid": "101210101", "Temp1": "1 ℃", "Temp2": "10 ℃", "Weather": "Cloudy to Clear", "IMG1": "N1.gif", "Img2": "D0.gif", "Ptime": "18:00"}, I wonder if any of my classmates follow my steps have got the above JSON data, Next we need to parse the above data on our Android! Lets go!

first, what is JSON?

JSON is a common XML-like data Interchange format, which has a higher transmission efficiency than XML, smaller volume, and can save traffic when the network is transmitted. But there are also drawbacks, which are less semantic than XML and look far less intuitive than XML.

Structurally, all data can eventually be decomposed into three types, but now it's basically a type of mapping (mapping), a name/value pair (Name/value), a name for the data, and a value corresponding to it. This is also known as hash (hash) or dictionary (dictionary), such as "Capital: Beijing". Its specifications are also very simple fixed.

(1) The data are separated by commas (","), such as "City": "Hangzhou", "Cityid": "101210101", between the city and the Cityid two data is separated by a

(2) The map is represented by a colon (":"). such as "City": "Hangzhou"

(3) a set (array) of side data is expressed in square brackets ("[]"). For example, if the returned data for several days, then the weather data will have several groups, will return similar to the following data form "Weatherinfo": [{"City": "Hangzhou", "Cityid": "101210101", "Temp1": " 1℃ "," Temp2 ":" 10 ℃ "," Weather ":" Cloudy to Clear "," IMG1 ":" N1.gif "," Img2 ":" D0.gif "," Ptime ":" 18:00 "},{" City ":" Hangzhou "," Cityid ":" 101210101 "," Temp1 ":" 1 ℃ "," Temp2 ":" 10 ℃ "," Weather ":" Cloudy to clear ", " IMG1 ":" N1.gif "," Img2 ":" D0.gif "," Ptime ":" 18:00 "}]

(4) The Set of Mappings (objects) are represented by curly braces ("{}"). For example, the Chinese weather net gives us the first thing to return is a whole weather object, and then it contains a Weatherinfo object.

second, how to parse JSON data?We first use the simplest method to parse the data returned by the Chinese Weather Network.

/** * Parses the JSON data returned by the server and stores the parsed data locally. */public static void Handleweatherresponse (context context, String response) {try {jsonobject jsonobject = new Jsonobject ( Response); Jsonobject weatherinfo = Jsonobject.getjsonobject ("Weatherinfo"); String CityName = weatherinfo.getstring ("city"); String Weathercode = weatherinfo.getstring ("Cityid"); String Temp1 = weatherinfo.getstring ("Temp1"); String Temp2 = weatherinfo.getstring ("Temp2"); String Weatherdesp = weatherinfo.getstring ("Weather"); String publishtime = weatherinfo.getstring ("Ptime"); Saveweatherinfo (context, CityName, Weathercode, Temp1, Temp2, Weatherdesp, publishtime);} catch (Jsonexception e) {e.printstacktrace ();}}

The response returned by the server is created by creating a Jsonobject object Jsonobject, and then by weatherinfo this key value to get the properties that it corresponds to Weatherinfo, then through the GetString () The value of the object is obtained by means of the key-value mapping method. Do you think it's a good problem to write? The code that has no brain operation has to be repeated several times.

third, use Gson to parse data?If you think that Jsonobject parsing JSON data is simple enough, you're just too easy to meet, Gson open source libraries can make parsing data incredibly simple! But at the beginning of everything you have to download the Gsonde jar package and import your own program files.

And then we'll look at the JSON data format we want to parse {"Weatherinfo": {"City": "Hangzhou", "Cityid": "101210101", "Temp1": "1 ℃", "Temp2": "10 ℃", "Weather": " Cloudy to clear "," IMG1 ":" N1.gif "," Img2 ":" D0.gif "," Ptime ":" 18:00 "}, according to its format we first define a weather class,

Package Com.melhc.model;public class Weather {private Weatherinfo weatherinfo;public weatherinfo getweatherinfo () { return weatherinfo;} public void Setweatherinfo (Weatherinfo weatherinfo) {this.weatherinfo = Weatherinfo;}}

Then there is a Weatherinfo object in this weather class, and this object contains the object of CITY,CITYID,TEMP1 and so on.

Package Com.melhc.model;public class Weatherinfo {private String city;   Private String Cityid;   Private String Temp1;   Private String Temp2; private string Weather;private string Ptime;public string getcity () {return city;} public void Setcity (String city) {this.city = city;} Public String Getcityid () {return Cityid;} public void Setcityid (String cityid) {This.cityid = Cityid;} Public String GetTemp1 () {return temp1;} public void SetTemp1 (String temp1) {this.temp1 = Temp1;} Public String getTemp2 () {return temp2;} public void SetTemp2 (String temp2) {this.temp2 = Temp2;} Public String GetWeather () {return weather;} public void Setweather (String weather) {this.weather = weather;} Public String Getptime () {return ptime;} public void Setptime (String ptime) {this.ptime = Ptime;} @Overridepublic String toString () {return "Weatherinfo [city=" + City + ", cityid=" + Cityid + ", temp1=" + Temp1 + ", temp 2= "+ Temp2 +", weather= "+ weather+", ptime= "+ Ptime +"] ";}}

as long as the definition of a Weatherinfo class, add city and so on the field into the class, and note that the data type of the property must correspond to each other will parse the failure, everything has, the rest will be given to Gson bar

public static void Handleweatherresponse (context context, String response) {try {Gson Gson = new Gson (); Weather Weather = Gson.fromjson (response, Weather.class); Weatherinfo info = weather.getweatherinfo (); Saveweatherinfo (context, info);} catch (Exception e) {//Todo:handle Exception}}

See not only three steps to complete the analysis of the data, there is no easy! We only need to map the data content to the specified class with the Gson,from () Method! so,easy! You may notice that there is a Saveweatherinfo method after the end of these three steps, and this method is used to do it!

public static void Saveweatherinfo (context context, Weatherinfo info) {SimpleDateFormat SDF = new SimpleDateFormat ("YYYY year M month D Day ", Locale.china); Sharedpreferences.editor Editor = preferencemanager.getdefaultsharedpreferences (context). edit (); Editor.putboolean ("city_selected", true); Editor.putstring ("City_name", info.getcity ()); Editor.putstring ("Weather_code", Info.getcityid ()); Editor.putstring ("Temp1", INFO.GETTEMP1 ()); Editor.putstring ("Temp2", INFO.GETTEMP2 ()); Editor.putstring ("Weather_desp", Info.getweather ()); Editor.putstring ("Publish_time", Info.getptime ()); Logutil.i ("UTILITY", "----------------->" +  sdf.format (new Date ())) editor.putstring ("Current_date", Sdf.format (New Date ())); Editor.commit ();}

This is how we use the Sharedpreference shared parameter to store the weather data we get on the day, so that users can read the data before they open, and then get the real-time weather data over the network when needed. , the Editor.put method can not directly store classes, only the basic data types, we can only put it here!

OK, the content of this lesson is here, but also hope that you can continue to support the series of blog posts, your support is my greatest motivation to write down! The content of today's Gson parsing data ends here, and the next blog post will soon meet you.

here is the git open source address for the app, Https://github.com/melhc/SimpleWeather

Get up and develop the weather software for Android (iv)--use Gson to parse 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.