Android: parses Json data
JSON (JavaScript Object Notation) is a lightweight data exchange format. when accessing the server, the returned data is often HTML, XML, and JSON. In this case, we need to parse the data. JSON has two structures: object and array. The former data format is {key: value, key: value ,...}; the latter data format is: ["java", "javascript", "vb",...], of course, the array can also be an object.
Example 1: Use the SDK class library to parse JSON data. The most important class is JsonReader. Its constructor is public JsonReader (Reader in ); the most important methods are beginArray (), beginObject (), hasNext (), nextString (), nextInt (), and the last end and close methods. It seems like parsing XML with SAX and PULL.
Create a tool class:
Package com. example. jsondemo; import java. io. IOException; import java. io. stringReader; import android. util. jsonReader; public class JsonUtils {public static void parseJson (String jsonData) {JsonReader reader = new JsonReader (new StringReader (jsonData); // instantiate a JsonReader object try {reader. beginArray (); // start to parse the array while (reader. hasNext () {// if the current array or object has elements, the true reader is returned. beginObject (); // starts parsing the object while (reader. hasNext () {String tagName = reader. nextName (); // print the parsed data if (tagName. equals ("name") {System. out. println ("-->" + reader. nextString ();} else if (tagName. equals ("age") {System. out. println ("-->" + reader. nextInt ();} reader. endObject (); // parse an object} reader. endArray (); // parse the array reader. close ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
Package com. example. jsondemo; import android. OS. bundle; import android. support. v7.app. actionBarActivity; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends ActionBarActivity {// [{\ "name \": \ "leelit \", \ "age \": 20 },{ \ "name \": \ "lina \", \ "age \": 21}] simulate the Json data returned by the server private String jsonData = "[{\" name \ ": \" leelit \", \ "age \": 20 },{ \ "name \": \ "lina \", \ "age \": 21}] "; // here/is the Escape Character @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button button = (Button) findViewById (R. id. button); button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {// TODO Auto-generated method stubSystem. out. println ("Begin to parse Json"); JsonUtils. parseJson (jsonData );}});}}
Result:
Resolution Process: [{"name": "leelit", "age": 20 },{ "name": "lina", "age": 21}]. Start to parse the array → parse the first object → tagName = "name", print out leelit → the first object has an element, and return true → tagName = "age ", print 20 → parse the first object and the second object, return the truth, and start to parse the second object, and so on.
Example 2: GSON is used to parse the JSON data containing an object, which is actually to convert the JSON data into a Java object. First download a GSON class library and click the open link. Then import it to the project: Put the jar file into the libs folder, right-click bulid path, and add path to use this GSON class library.
Create a User class:
package com.example.jsondemo;public class User {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
Create a tool class:
Package com. example. jsondemo; import java. io. stringReader; import com. google. gson. gson; import android. util. jsonReader; public class JsonUtils {public static void parseJson (String jsonData) {Gson gson = new Gson (); // instantiate a GSON Object User user = gson. fromJson (jsonData, User. class); // gson is used to convert JSON data into a JavaBean object. System. out. println ("-->" + user. getName () + "" + user. getAge ());}}
package com.example.jsondemo;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends ActionBarActivity {// {"name":"leelit","age":20};private String jsonData = "{\"name\":\"leelit\",\"age\":20}";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button button = (Button) findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubSystem.out.println("Begin to parse Json");JsonUtils.parseJson(jsonData);}});}}
Result:
Example 3: Use GSON to parse array JSON data
Create a User class <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + 0MK9qNK7uPa5pL7fwOA8L3A + CjxwPjxwcmUgY2xhc3M9 "brush: java;"> package com. example. jsondemo; 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 static void parseJson (String jsonData) {Type listType = new TypeToken > () {}. GetType (); Gson gson = new Gson (); Aggregate list Users = gson. fromJson (jsonData, listType); // converts Json data into a jsonlist object for (User user: users) {System. out. println ("-->" + user. getName () + "" + user. getAge ());}}}
package com.example.jsondemo;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends ActionBarActivity {// [{\"name\":\"leelit\",\"age\":20},{\"name\":\"lina\",\"age\":21}]private String jsonData = "[{\"name\":\"leelit\",\"age\":20},{\"name\":\"lina\",\"age\":21}]";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button button = (Button) findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubSystem.out.println("Begin to parse Json");JsonUtils.parseJson(jsonData);}});}}
Result:
Conclusion: You can familiarize yourself with the JsonReader and Gson classes. Many of the video tutorials are self-built servers, and then the returned data is parsed by themselves. This should be more profound, but it is still not a server. Another method we know is to use FastJson for parsing, so we will not learn it first.