The--android of JSON parsing

Source: Internet
Author: User

The--android of JSON parsing

First, the Google weather case

The Google weather example before XML learning is very image, so we continue to use Google weather as a case study, the following is my download from the Google website weather json file, you can see, and XML format is very different.

1 {"Coord": {"lon": 121.46, "lat": 31.22},2 "Weather": [{3 "id": 721,4 " main": "Haze",5 " description": "Haze",6 " icon": "50d"}],7 "base": "Stations",8 "main":9 {"Temp": 282.15,Ten "Pressure": 1024x768, One "Humidity": A "Temp_min": 282.15, - "Temp_max": 282.15}, - "Visibility": 4500, the "Wind": {"Speed": 5, "deg": 310}, - "Clouds": {"all": +}, - "DT": 1450060200, - "sys": { + "type": 1, - "id": 7452, + "message": 0.0142, A "Country": "CN", at "Sunrise": 1450046656, - "Sunset": 1450083169}, - "id": 1796236, - "name": "Shanghai", - "Cod": -}

The data we need are: City lowest temperature maximum temperature humidity wind direction

So we set up a Currentweatherjson class to store the data we need.

1  PackageOrg.xerrard.xmlpulldemo;2 3  Public classCurrentweatherjson {4 5     6      PublicString City;//City7      PublicString temperature_min;//Temperature8      PublicString Temperature_max;//Temperature9      PublicString humidity;//HumidityTen      PublicString wind_direction;//Wind Direction One      A      PublicString toString () -     { -         //Celsius (℃) =k-273.  the         floatTemperaturemin = Float.parsefloat (temperature_min) -272.15f; -         floatTemperaturemax = Float.parsefloat (Temperature_max) -272.15f; -          -StringBuilder SB =NewStringBuilder (); +Sb.append ("City:"). Append (city); -Sb.append ("Lowest temperature:"). Append (Temperaturemin + ""). Append ("°c"); +Sb.append ("Maximum temperature:"). Append (Temperaturemax + ""). Append ("°c"); ASb.append ("humidity"). append (humidity); atSb.append ("Wind Direction"). Append (wind_direction); -         returnsb.tostring (); -     } -}

Then we set up a data model to encapsulate the parsing of JSON data, and in Weatherjsonmodel we can parse the data we need in JSON and store it in the Currentweatherjson object.

1  PackageOrg.xerrard.xmlpulldemo;2 3 Importorg.json.JSONException;4 ImportOrg.json.JSONObject;5 ImportOrg.json.JSONTokener;6 7  Public classWeatherjsonmodel {8 9      Public StaticCurrentweatherjson GetData (String json) {TenJsontokener Jsonparser =NewJsontokener (JSON); One jsonobject weather; A         Try { -Weather =(Jsonobject) jsonparser.nextvalue (); -             if(Weather.length () >0){ theCurrentweatherjson curcondition =NewCurrentweatherjson (); -Curcondition.city = weather.getstring ("name"); -Curcondition.humidity = Weather.getjsonobject ("main"). GetInt ("humidity") + ""; -Curcondition.temperature_max = Weather.getjsonobject ("main"). GetInt ("Temp_max") + ""; +Curcondition.temperature_min = Weather.getjsonobject ("main"). GetInt ("temp_min") + ""; -Curcondition.wind_direction = Weather.getjsonobject ("Wind"). GetInt ("deg") + ""; +             } A         } at         Catch(jsonexception e) { -             //TODO auto-generated Catch block - e.printstacktrace (); -         } -         returncurcondition;  -          in         -  to     } +      -}

Finally, we can use Weatherjsonmodel to parse the data and get the data we need.

1File Jsonflie =NewFile (Environment.getexternalstoragedirectory (). GetPath () + "/" + "Weather.json"); 2Charbuffer Cbuf =NULL; 3 FileReader Freader;4         Try {5Freader =NewFileReader (Jsonflie);6Cbuf = Charbuffer.allocate ((int) jsonflie.length ()); 7 Freader.read (CBUF); 8String Text =NewString (Cbuf.array ()); 9TextView Hello =(TextView) Findviewbyid (R.id.hello);Ten Hello.settext (Weatherjsonmodel.getdata (text). toString ()); One         } A         Catch(FileNotFoundException e) { -             //TODO auto-generated Catch block - e.printstacktrace (); the         } -         Catch(IOException e) { -             //TODO auto-generated Catch block - e.printstacktrace (); +}

Ii. Several of the more important classes provided by JSON in Android

The JSON parsing part of Android is under package Org.json, mainly in the following categories:
jsonobject: Can be thought of as a JSON object, which is the basic unit of JSON definition in the system, which contains a pair of child (Key/value) values. Its response to the external (External: Apply the ToString () method output value) is reflected as a standard string (for example: {"JSON": "Hello, World"}, enclosing the outer brace with the key and value separated by the colon ":"). Its action format for internal (Internal) behavior is slightly, for example: Initializing a Jsonobject instance, referencing the internal put () method to add a value: New Jsonobject (). Put ("JSON", "Hello, world!"), Between key and value is separated by a comma ",". The types of value include: Boolean, Jsonarray, Jsonobject, number, string, or the default value Jsonobject.null object.

Jsonstringer: JSON text build class, according to the official explanation, this class can help to create JSON text quickly and conveniently. The biggest advantage is that you can reduce program exceptions due to malformed formatting, and referencing this class automatically creates JSON text in strict accordance with the JSON syntax rules (syntax rules). Each Jsonstringer entity can only be created with one JSON text: The biggest advantage is that you can reduce program exceptions due to malformed formatting, and referencing this class automatically creates JSON text in strict accordance with the JSON syntax rules (syntax rules). Each Jsonstringer entity can only create one JSON text.

Jsonarray: It represents an ordered set of values. Converting it to a string output (toString) is performed in the form of a square bracket, separated by a comma "," (for example: [Value1,value2,value3], you can personally use the short code to understand its format more intuitively). The inside of this class also has query behavior, both get () and opt () can return the specified value through the index index, and the put () method is used to add or replace values. Similarly, the value type of this class can include: Boolean, Jsonarray, Jsonobject, number, string, or Default value Jsonobject.null object.

Jsontokener: JSON parsing class
jsonexception: Exceptions used in JSON

Third, for the analysis of complex JSON data, Google provides gson to deal with.

Resources:

Google Weather Api:http://openweathermap.org/current

http://blog.csdn.net/onlyonecoder/article/details/8490924 Android JSON parsing detailed

The--android of JSON parsing

Related Article

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.