Android JSON format data parsing and androidjson Parsing

Source: Internet
Author: User

Android JSON format data parsing and androidjson Parsing
JSON: JavaScript Object Notation (JavaScript Object Notation ). Independent of languages and platforms, it is smaller, faster, and easier to parse than XML. Nowadays, JSON data has become a transmission mode for a large majority of data on the Internet, so you must be familiar with it.

The Android platform comes with APIs related to JSON parsing. You can convert data in files and input streams to JSON objects, and then obtain the data stored in JSON from the objects.


The JSON parsing section of Android is in the org. json package, which mainly includes the following classes:
JSONObject: It can be viewed as a json object, which is the basic unit related to the json definition in the system. It contains a pair of Key/Value values. Its response to an External call (External: Applying the value output by the toString () method) is a standard string (for example, {"JSON": "Hello, World "}, the outmost is enclosed by braces, and the Key and Value are separated by the colon ). The operation format for Internal (Internal) behaviors is slightly. For example, to initialize a JSONObject instance, reference the Internal put () method to add a value: new JSONObject (). put ("JSON", "Hello, World! "), Separated by commas (,) between keys and values. Value types include: Boolean, JSONArray, JSONObject, Number, String, or the default Value JSONObject. NULL object.

JSONStringer: Json text Build class. According to official explanations, this class can help you quickly and conveniently create JSON text. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON text in strict accordance with the JSON syntax rules (syntax rules. Each JSONStringer object can only create one JSON text .. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON text in strict accordance with the JSON syntax rules (syntax rules. Each JSONStringer object can only create one JSON text.

JSONArray: It represents a group of ordered values. The format of toString output is enclosed in square brackets. Values are separated by commas (,) ([value1, value2, value3], you can use the short code to learn more about the format ). This class has the same internal query behavior. The get () and opt () methods can both return the specified value through the index, and the put () method is used to add or replace the value. The value Type of this class can also include: Boolean, JSONArray, JSONObject, Number, String, or the default value JSONObject. NULL object.

JSONTokener: Json parsing class
JSONException: Exceptions used in json

The following uses the aggregated data Air Quality City Air PM2.5 index data interface as an example to demonstrate the JSON format data parsing.
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 return example:
{/* JSONObject */
"Resultcode": "200 ",
"Reason": "SUCCESSED! ",
"Result": [/* JSONArray */
{/* JSONObject */
"City": "Suzhou",/* city */
"PM2.5": "73",/* PM2.5 Index */
"AQI": "98",/* Air Quality Index */
"Quality": "Good",/* Air quality */
"PM10": "50",/* PM10 */
"CO": "0.79",/* carbon monoxide */
"NO2": "65",/* Nitrogen Dioxide */
"O3": "28",/* ozone */
"SO2": "41",/* sulfur dioxide */
"Time": "11:48:40"/* Update time */
}
],
"Error_code": 0
}

Example: JSONDemo
Running effect:

Code List:
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: orientation = "vertical" tools: context = ". mainActivity "> <LinearLayout android: layout_width =" match_parent "android: layout_height =" wrap_content "android: orientation =" horizontal "> <TextView android: layout_width =" wrap_content "android: layout_height = "wrap_content" android: layout_weight = "1" android: gravity = "center" android: text = "City:" android: textSize = "23sp"/> <EditText android: id = "@ + id/city" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_weight = "3" android: inputType = "text"/> "</LinearLayout> <Button 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 = "match_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 city = et_city.getText (). toString (); if (city. length () <1) {Toast. makeText (MainActivity. this, "enter the city name", Toast. LENGTH_LONG ). show (); return;} task = new QueryTask (MainActivity. this, TV _result); task.exe cute (city) ;}}) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action 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/e Export ronment/air/pm "; private static final String JUHE_APPKEY =" Your applied APPKEY value "; 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> (); headerL Ist. 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", 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 

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"> city </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 time </string> </resources>


API knowledge point
Public class
JSONObject
Extends Object

Org. json. JSONObject

Class Overview
A modifiable set of name/value mappings. names are unique, non-null strings. values may be any mix of JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles or NULL. values may not be null, NaNs, infinities, or of any 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 is 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 be any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL. values may not be NaNs, infinities, or of any type not listed here.

JSONObject getJSONObject (int index)

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


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.