Android JSON data parsing

Source: Internet
Author: User

Android JSON data parsing
Software and hardware environment

  • Macbook Pro MGX 72
  • Android Studio 1.3.2
  • Genymotion Simulator
Preface

Today, few apps do not deal with servers. In lightweight communication, JSON (JavaScript Object Notation) and XML, this document describes JSON-related knowledge.

JSON object

Objects in JSON are included in a pair of braces. Each item in the object is a "key: value" Data pair, which is separated by commas. The key of a JSON object can only be of the String type. value may be of another type, such as number, boolean, or null. As shown below

{    "Name" : "Alex",    "Sex"  : "Male",    "Age"  : "20",}
JSON Array

The JSON array is included in a pair of brackets. Each element is a JSON object separated by commas (,). The example is as follows:

[    {    "Name" : "Alex",    "Sex"  : "Male",    "Age"  : "20",    },    {    "Name" : "May",    "Sex"  : "Female",    "Age"  : "19",    },    {    "Name" : "Mike",    "Sex"  : "Male",    "Age"  : "21",    }]
Basic FastJSON usage

FastJSON is a framework developed by alibaba for JSON parsing. Based on their own tests, FastJSON is fast and efficient, and is not among them. We take from the aggregation Data website query SuZhou city weather forecast of a JSON data as an example to explain, the obtained URL address is http://v.juhe.cn/weather/index? Format = 2 & cityname = % E8 % 8B % 8F % E5 % B7 % 9E & key = 6f9276e4d79c5d102bbfb28717beba93. To ensure that there is no problem with the data source, open the URL in the browser to see if there is any data. Here we will introduce the JSON Accelerator, a Mac tool, which not only captures data from the network, but also adds http request header information, which is very convenient to use.

Create a project

The new project is named FastJSONDemo. to access the network, you need to add the corresponding permissions in AndroidManifest. xml.

<uses-permission android:name="android.permission.INTERNET" />
Code Section

Network request section. Here we use the volley library, which is produced by Google and easy to use. Source code example. After the download, the volley library is imported into the project. If the UI is used, a TextView is used to display the received json data.

To create a global Request queue, you must implement a subclass inherited from the Application called VolleyApplication.

Package com. djstava. fastjsondemo; import android. app. application; import com. android. volley. requestQueue; import com. android. volley. toolbox. volley;/*** package name: com. djstava. created by fastjsondemo *: djstava * Creation Time: 15/9/23 */public class VolleyApplication extends Application {public static RequestQueue requestQueue; @ Override public void onCreate () {super. onCreate (); requestQueue = Volley. newRequestQueue (getApplicationContext ();} public static RequestQueue getVolleyQueue () {return requestQueue ;}}

Write the request part in the onStart method of MainActivity, and then cancel the request in the onStop method.

Private static final String JSON_URL = "http://v.juhe.cn/weather/index? Format = 2 & cityname = % E8 % 8B % 8F % E5 % B7 % 9E & key = 6f9276e4d79c5d102bbfb28717beba93 "; // The Field key is applied from the aggregate data website, replace @ Overrideprotected void onStart () {super. onStart (); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Request. method. GET, JSON_URL, null, new Response. listener <JSONObject> () {@ Override public void onResponse (JSONObject jsonObject) {try {textView. setText (jsonObject. toString (); Log. e (TAG, "result:" + jsonObject. getString ("resultcode");} catch (JSONException e) {e. printStackTrace () ;}}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError volleyError) {Log. e (TAG, volleyError. getMessage () ;}}); jsonObjectRequest. setTag ("fastjson"); VolleyApplication. requestQueue. add (jsonObjectRequest) ;}@ Overrideprotected void onStop () {super. onStop (); VolleyApplication. requestQueue. cancelAll ("fastjson ");}

Do not forget to add it to the Application tag of the AndroiManifest. xml file.

android:name=".VolleyApplication"

Run the program on the Genymotion simulator to view the obtained data.

To facilitate the reader's viewing, use the JSON Accelerator to format it.

{"Result": {"sk": {"humidity": "58%", "wind_direction": "northwest wind", "temp": "26", "wind_strength ": "Level 2", "time": "17:27"}, "today": {"temperature": "22 ℃ ~ 27 ℃ "," dressing_index ":" comfortable "," dressing_advice ":" We recommend that you wear long-sleeved t-shirts, shirts, and trousers. The elderly and inner should have knitted long-sleeved shirts, vests and trousers. "," Uv_index ":" weak "," comfort_index ":" "," wind ":" northeast wind 3-4 "," weather ":" Multi-cloud to shower ", "city": "Suzhou", "date_y": "September 24, 2015", "week": "Thursday", "pai_index": "Not suitable", "weather_id ": {"fa": "01", "fb": "03"}, "travel_index": "More suitable", "exercise_index": "More suitable", "drying_index ": ""}, "future": [{"temperature": "22 ℃ ~ 27 ℃ "," weather_id ": {" fa ":" 01 "," fb ":" 03 "}," wind ":" Northeast 3-4 ", "week": "Thursday", "date": "20150924", "weather": "Multi-cloud to shower" },{ "temperature": "21 ℃ ~ 26 ℃ "," weather_id ": {" fa ":" 03 "," fb ":" 01 "}," wind ":" Northeast 3-4 ", "week": "Friday", "date": "20150925", "weather": "shower to multi-cloud" },{ "temperature": "21 ℃ ~ 27 ℃ "," weather_id ": {" fa ":" 01 "," fb ":" 01 "}," wind ":" Northeast 3-4 ", "week": "Saturday", "date": "20150926", "weather": "multi cloud" },{ "temperature": "21 ℃ ~ 28 ℃ "," weather_id ": {" fa ":" 00 "," fb ":" 00 "}," wind ":" Northeast 3-4 ", "week": "Sunday", "date": "20150927", "weather": "Qing" },{ "temperature": "22 ℃ ~ 28 ℃ "," weather_id ": {" fa ":" 01 "," fb ":" 01 "}," wind ":" Dongfeng 3-4 ", "week": "Monday", "date": "20150928", "weather": "multi cloud" },{ "temperature": "22 ℃ ~ 28 ℃ "," weather_id ": {" fa ":" 01 "," fb ":" 03 "}," wind ":" Dongfeng 3-4 ", "week": "Tuesday", "date": "20150929", "weather": "Multi-cloud to shower" },{ "temperature": "20℃ ~ 25℃ "," weather_id ": {" fa ":" 04 "," fb ":" 04 "}," wind ":" southeast wind 4-5 ", "week": "weather", "date": "20150930", "weather": "thundershower"}]}, "resultcode": "200", "reason ": "successed! "," Error_code ": 0}

The next step is fastjson. first go to the release.

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSON_URL, null,            new Response.Listener<JSONObject>() {                @Override                public void onResponse(JSONObject jsonObject) {                    try {                        textView.setText(jsonObject.toString());                        com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(jsonObject.toString());                        for (Map.Entry<String, Object> entry : jsonObject1.entrySet()) {                            System.out.println(entry.getKey() + ":" + entry.getValue());                        }                    } catch (Exception e) {                        e.printStackTrace();                    }                }            }, new Response.ErrorListener() {        @Override        public void onErrorResponse(VolleyError volleyError) {            Log.e(TAG, volleyError.getMessage());        }    });

In this way, simple data parsing is complete.

What is JavaBean?

JavaBean is a java component that complies with certain specifications, that is, a java class. It must meet the following requirements:

  • There is a default constructor with no parameters
  • Get and set methods

We abstract company employees into a class and use fastjson for parsing.

Package com. djstava. fastjsondemo;/*** package name: com. djstava. created by fastjsondemo *: djstava * Creation Time: 15/9/28 am */public class Employee {private int num; private String name; private int age; public Employee (int num, string name, int age) {this. num = num; this. name = name; this. age = age;} public void setNum (int num) {this. num = num;} public void setName (String name) {this. name = name;} public void setAge (int age) {this. age = age;} public int getNum () {return num;} public String getName () {return name;} public int getAge () {return age ;} @ Override public String toString () {return "Employee {" + "num =" + num + ", name = '" + name +' \ ''+ ", age = "+ age + '}';}}

In Android Studio, you can automatically Generate get, set, and toString methods, Code-> Generate, And the shortcut key is Command + N.

Employee employee  = new Employee(1,"djstava",20);Log.e(TAG,JSON.toJSONString(employee));

It can be seen that the output json format is inconsistent with the order of the attributes defined in our class. In fact, it does not matter. json obtains the corresponding value through the key.

If you only want to parse several fields in the JavaBean class, you can use the SimplePropertyPreFilter class to add the fields to be parsed, for example, parse "num" and "name" in the Employee class

SimplePropertyPreFilter simplePropertyPreFilter = new SimplePropertyPreFilter(Employee.class,"num","name");Log.e(TAG,JSON.toJSONString(employee,simplePropertyPreFilter));

Source code download

Http://download.csdn.net/detail/djstavav/9144789

References

1. http://www.json.org/
2. https://github.com/alibaba/fastjson/wiki
3. https://www.juhe.cn/docs/api/id/39

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.