Android JSON Format data parsing

Source: Internet
Author: User

Json:javascript Object Notation (JavaScript object Notation). Language and platform independent, smaller, faster, and easier to parse than XML. Now that JSON data has become the way most of the data in the Internet is delivered, it must be mastered.

The Android platform comes with a JSON-parsed API that converts data from files, input streams into JSON objects, and then obtains JSON-saved data content from objects.


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 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, which, according to the official explanation, can help create JSON text quickly and easily. 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

The following example illustrates the parsing of JSON-formatted data using the data interface of the urban air PM2.5 index for aggregated data air quality.
Aggregated data air quality City Air PM2.5 index data Interface API documentation see: HTTP://WWW.JUHE.CN/DOCS/API/ID/33/AID/79
JSON returns an example:
{/*jsonobject*/
"ResultCode": "200",
"Reason": "successed!",
"Result": [/*jsonarray*/
{/*jsonobject*/
"City": "Suzhou",/* Cities * *
"PM2.5": "/*pm2.5", Index */
"AQI": "98",/* Air quality Index */
"Quality": "Liang",/* air quality */
"PM10": "/*pm10*/"
"CO": "0.79",/* carbon monoxide */
"NO2": "65",/* nitrogen dioxide */
"O3": "28",/* Ozone */
"SO2": "41",/* sulfur dioxide */
"Time": "2014-12-26 11:48:40"/* Update times */
}
],
"Error_code": 0
}

Example: Jsondemo
Operating effect:

Code Listing:
Layout file: Activity_main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "Vertical" tools:context= ". Mainactivity "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_cont Ent "android:orientation=" horizontal "><textview android:layout_width=" Wrap_content "android:layout_he ight= "Wrap_content" android:layout_weight= "1" android:gravity= "center" android:text= "City:" Android:textsize= "23 SP "/><edittext android:id=" @+id/city "android:layout_width=" Wrap_content "Android:layout_heig ht= "Wrap_content" android:layout_weight= "3" android:inputtype= "text"/> "</LinearLayout> <butt         On android:id= "@+id/query" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "Query" android:textsize= "23sp"/> <textviewandroid:id= "@+id/result" android:layout_width= "MATC H_parent "android:layout_height=" Match_parent "/></linearlayout>

Java source code file: Mainactivity.java
Package Com.rainsong.jsondemo;import Android.os.bundle;import Android.app.activity;import android.view.Menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;public class MainActivity    Extends Activity {EditText et_city;    Button Btn_query;    TextView Tv_result;    Querytask task;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Et_city = (EditText) Findviewbyid (r.id.city);        Tv_result = (TextView) Findviewbyid (R.id.result);        Btn_query = (Button) Findviewbyid (r.id.query); Btn_query.setonclicklistener (New Onclicklistener () {public void OnClick (view view) {String CIT                y = Et_city.gettext (). toString (); if (City.length () < 1) {Toast.maketext (Mainactivity.this, "Please enter city name", Toast.length_long). Show ();                Return                } task = new Querytask (mainactivity.this, Tv_result);            Task.execute (city);    }        }); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; }}

Java source code file: Querytask.java
Package Com.rainsong.jsondemo;import Java.io.ioexception;import Java.net.urlencoder;import java.util.ArrayList; Import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import org.apache.http.client.HttpClient ; Import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.util.entityutils;import Org.json.JSONArray; Import Org.json.jsonexception;import Org.json.jsonobject;import Android.content.context;import Android.os.asynctask;import Android.widget.textview;import Android.widget.toast;public class QueryTask extends    Asynctask<string, Void, string> {context context;    TextView Tv_result; private static final String juhe_url_environment_air_pm = "http://web.juhe.cn:8080/env    IRONMENT/AIR/PM ";    private static final String Juhe_appkey = "The APPKEY value you applied for"; Public Querytask (context context, TextView Tv_result) {// TODO auto-generated Constructor stub super ();        This.context = context;     This.tv_result = Tv_result;        } @Override protected String Doinbackground (String ... params) {string city = Params[0];        arraylist<namevaluepair> headerlist = new arraylist<namevaluepair> (); Headerlist.add (New Basicnamevaluepair ("Content-type", "text/html;        Charset=utf-8 "));        String targeturl = juhe_url_environment_air_pm;        arraylist<namevaluepair> paramlist = new arraylist<namevaluepair> ();        Paramlist.add (New Basicnamevaluepair ("key", Juhe_appkey));        Paramlist.add (New Basicnamevaluepair ("Dtype", "JSON"));        Paramlist.add (New Basicnamevaluepair ("City");            for (int i = 0; i < paramlist.size (); i++) {Namevaluepair Nowpair = Paramlist.get (i);            String value = Nowpair.getvalue ();            try {value = Urlencoder.encode (value, "UTF-8"); } catch (Exception e){} if (i = = 0) {TargetUrl + = ("?" + nowpair.getname () + "=" + value);            } else {TargetUrl + = ("&" + nowpair.getname () + "=" + value);        }} httpget HttpRequest = new HttpGet (targeturl); try {for (int i = 0; i < headerlist.size (); i++) {Httprequest.addheader (Headerlist.get (i). g            Etname (), Headerlist.get (i). GetValue ());            } HttpClient HttpClient = new Defaulthttpclient ();            HttpResponse HttpResponse = Httpclient.execute (HttpRequest); if (Httpresponse.getstatusline (). Getstatuscode () = = () {String strresult = entityutils.tostring (httpresp                Onse.getentity ());            return strresult;            } else {return null;        }} catch (IOException e) {e.printstacktrace ();    } return null; } @Override ProtecTed void OnPostExecute (String result) {if (result! = null) {try {jsonobject Jsonobject                = new Jsonobject (result);                int resultcode = Jsonobject.getint ("ResultCode");                    if (ResultCode = =) {Jsonarray Resultjsonarray = Jsonobject.getjsonarray ("result");                    Jsonobject resultjsonobject = resultjsonarray.getjsonobject (0);                            String output = context.getstring (r.string.city) + ":" + resultjsonobject.getstring ("city") + "\ n" + context.getstring (R.STRING.PM25) + ":" + resultjsonobject.getstring ("PM2.5") + "\ n" + C Ontext.getstring (R.string.aqi) + ":" + resultjsonobject.getstring ("AQI") + "\ n" + context.gets Tring (r.string.quality) + ":" + resultjsonobject.getstring ("quality") + "\ n" + Context.getstri      Ng (R.STRING.PM10) + ":" + resultjsonobject.getstring ("PM10") + "\ n"                      + context.getstring (r.string.co) + ":" + resultjsonobject.getstring ("CO") + "\ n" + context.getstring (R.string.no2) + ":" + resultjsonobject.getstring ("NO2") + "\ n" + Context.getstring (R.STRING.O3) + ":" + resultjsonobject.getstring ("O3") + "\ n" + context.getst Ring (R.STRING.SO2) + ":" + resultjsonobject.getstring ("SO2") + "\ n" + context.getstring (R.stri                    Ng.time) + ":" + resultjsonobject.getstring ("time") + "\ n";                Tv_result.settext (output);                    } else if (ResultCode = = 202) {String reason = jsonobject.getstring ("Reason");                Tv_result.settext (reason);                    } else {Toast.maketext (context, "Query failed", Toast.length_long). Show ();                Tv_result.settext (""); }} catch (Jsonexception e) {//TODO auto-generated Catch block E.printstacktrace ();             }} else {Toast.maketext (context, "Query failed", Toast.length_long). Show ();        Tv_result.settext (""); }    }    }

String resource: String.xml

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <string name= "App_name" >jsondemo</ string>    <string name= "action_settings" >Settings</string>    <string name= "Hello_world" >hello world!</string>    <string name= "City" > Cities </string>    <string name= "PM25" > PM2.5 index </string>    <string name= "AQI" > Air quality index </string>    <string name= "quality" > Air quality </string>    <string name= "PM10" >PM10</string>    <string name= "CO" > Carbon monoxide </string >    <string name= "NO2" > Nitrogen dioxide </string>    <string name= "O3" > Ozone </string>    < String name= "SO2" > Sulfur dioxide </string>    <string name= "Time" > Update times </string>    </resources >


API Knowledge Points
public class
Jsonobject
Extends Object

Org.json.JSONObject

Class Overview
A modifiable set of name/value mappings. Names is unique, non-null strings. Values May is any mix of jsonobjects, Jsonarrays, Strings, booleans, integers, Longs, doubles or NULL. Values May is not a null, NaNs, infinities, or of any of the type not listed here.

Jsonobject (String JSON)
Creates a new jsonobject with name/value mappings from the JSON string.

Object get (String name)
Returns the value mapped by name.

int getInt (String name)
Returns the value mapped by name if it exists and was an int. or can be coerced to an int.

String getString (string name)
Returns the value mapped by name if it exists, coercing it if necessary.

Jsonarray Getjsonarray (String name)
Returns the value mapped by name if it exists and is a jsonarray.

public class
Jsonarray
Extends Object

Org.json.JSONArray

Class Overview
A dense indexed sequence of values. Values May is any mix of jsonobjects, other jsonarrays, Strings, booleans, integers, Longs, doubles, null or NULL. Values may isn't nans, infinities, or of any of the type not listed here.

Jsonobject getjsonobject (int index)

Returns the value at index if it exists and is a jsonobject.


Android JSON Format data parsing

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.