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 strike the hot and finish 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 do not know if the classmate followed my steps have gotten the above JSON data, next we need to in our Android on the above data parsing! Lets go!

first, what is JSON?

JSON is a common data interchange format similar to XML, which has higher transmission efficiency than XML, smaller volume, and can save traffic in network transmission. But there are also drawbacks, which are worse than the semantics of XML. Looks far less intuitive than XML.

Structurally, all of the data can finally be decomposed into three types, but today it's basically a type of mapping (mapping), a name/value pair (Name/value), where the data has a name, and the other corresponding value, This is also known as hash (hash) or dictionary (dictionary), for example "Capital: Beijing". Its specifications are also very easy to fix.

(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, assuming that the data returned for several days, the weather data will be 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 to return to us first is a whole is weather object. It then includes 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 it weatherinfo, then by GetString () The value of the object is obtained by means of the key-value mapping method.

Do you think it is very difficult to write. There are repeated AH. The code that has no brain operation has to be repeated several times.

third, use Gson to parse data?     Assuming you think Jsonobject parsing JSON data is simple enough, you're just too easy to meet, Gson open source libraries can make parsing data incredibly simple!

It's just the beginning of everything. 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 includes 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 +"] ";}}

just to define a Weatherinfo class, add city and so on to the class. And note that the data type of the property should be the corresponding or will resolve the failure, everything has. The rest of you, just give it to Gson.

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 there is no need to just three steps to complete the analysis of the data. There is no very easy it!

We only have to be able to map the data content to the specified class by using the Gson,from () Method! so,easy! You may notice another Saveweatherinfo method after the end of these three steps. What is this method for?


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 sharedpreference shared parameters to store the weather data we get on the day, so that users can read the data they received before they open it, and then get the real-time weather data over the network when they need it. The Editor.put method cannot store classes directly. Only the main data types can be stored, and we can just put them here.

Okay, good. Here's what this lesson says. I also hope that we can continue to support this series of blog posts. Your support is the greatest motivation I have written down! Today's Gson analysis of the content of the data to this end, the next post will be very quick to meet with you.

here is the git open source address for the app. Https://github.com/melhc/SimpleWeather 2014 blog star please support it. Http://vote.blog.csdn.net/blogstar2014/details?

Username=u013900875#content

To 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.