Android _ uses Gson to parse json data and gsonjson

Source: Internet
Author: User

Android _ uses Gson to parse json data and gsonjson

Json is a common data exchange format similar to XML, with higher transmission efficiency than XML.
In terms of structure, all data can be divided into three types:

The first type is scalar, which is a separate string or number, such as the word "Beijing.
The second type is sequence, that is, several related data are grouped together in a certain order, also called array or List, for example, "Beijing, shanghai ".
The third type is mapping, that is, a Name/value pair (Name/value). That is, the data has a Name and a corresponding value, this is also called hash or dictionary, for example, "capital: Beijing ".
The Json specification is very simple. It can be clearly stated in just a few hundred words on a page, and Douglas Crockford claims that this specification will never need to be upgraded, because it is stipulated in this provision.
1) Separate the parallel data with commas.
2) The ing is represented by a colon.
3) The set (array) of the parallel data is represented by square brackets.
4) The ing set (object) is represented by braces.

In Android, Gson can be used to parse JSON data.
First, download gsonapi: google-gson2.2.4.rar from code.google.com/p/google-gson/downloads/list
Copy the gson-2.2.4.jar to libs (the project root directory creates a new libs folder.
You can use either of the following methods to parse JSON data:
1. parse JSON data by obtaining the JsonReader object:
MainActivity. java:

package ycw.json01;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private String jsonData = "[{\"name\":\"Yen\",\"age\":22},{\"name\":\"Lee\",\"age\":24}]";private Button btn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn = (Button) findViewById(R.id.btn01);btn.setOnClickListener(this);}@Overridepublic void onClick(View v) {if (v.getId() == R.id.btn01) {JsonUtils ju = new JsonUtils();ju.parseJson(jsonData);}}}
JsonUtils. java:
Package ycw. json01; import java. io. stringReader; // import android. util. jsonReader; import com. google. gson. stream. jsonReader; public class JsonUtils {public void parseJson (String jsonData) {try {// If json data needs to be parsed, first, you must generate a JsonReader object JsonReader reader = new JsonReader (new StringReader (jsonData); reader. beginArray (); while (reader. hasNext () {reader. beginObject (); while (reader. hasNext () {String tagName = reader. nextName (); if (tagName. equals ("name") {System. out. println ("name --->" + reader. nextString ();} else if (tagName. equals ("age") {System. out. println ("age --->" + reader. nextString ();} reader. endObject ();} reader. endArray ();} catch (Exception e) {e. printStackTrace ();}}}
2. Map JSON data into an object and use the fromJson () method of the Gson object to obtain an object array for operations:
Create a POJO object UserModel. java corresponding to JSON data:
package ycw.json02;public class UserModel {private String name;private String age;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}}
Use the Gson object to obtain User object data for corresponding operations:
MainActivity. java:
package ycw.json02;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private String jsonData = "[{\"name\":\"Yen\",\"age\":22},{\"name\":\"Lee\",\"age\":24}]";private String jsonData2= "{\"name\":\"Yen\",\"age\":22}";private Button btn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn = (Button) findViewById(R.id.btn02);btn.setOnClickListener(this);}@Overridepublic void onClick(View v) {if (v.getId() == R.id.btn02) {JsonUtils ju = new JsonUtils();ju.parseUserFromJson(jsonData);ju.parseUserFromJson2(jsonData2);}}}
JsonUtils. java:
Package ycw. json02; import java. lang. reflect. type; import java. util. iterator; import java. util. using list; import com. google. gson. gson; import com. google. gson. reflect. typeToken; public class JsonUtils {public void parseUserFromJson (String jsonData) {Type listType = new TypeToken <shortlist <UserModel> (){}. getType (); Gson gson = new Gson (); writable list <UserModel> users = gson. fromJson (jsonData, listType); for (Iterator iterator = users. iterator (); iterator. hasNext ();) {UserModel user = (UserModel) iterator. next (); System. out. println ("name -->" + user. getName (); System. out. println ("age -->" + user. getAge () ;}// the processed JSON String contains only one JSON object. You can use fromJson to obtain a User object public void parseUserFromJson2 (String jsonData) {Gson gson = new Gson (); UserModel user = gson. fromJson (jsonData, UserModel. class); System. out. println ("name->" + user. getName (); System. out. println ("age->" + user. getAge ());}}

More ---> http://blog.csdn.net/linjiaxingqqqq/article/details/7238235

Welcome to http://blog.csdn.net/ycwol/article/details/46318831

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.