Android Network data parsing-use Google Gson to parse Json data

Source: Internet
Author: User

Android Network data parsing-use Google Gson to parse Json data
I. Introduction to Json data Json (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JS. Json adopts a language-independent text format, which makes Json an ideal data exchange language. Easy for reading and writing, and easy for machine parsing and generation. Json is simply an object and an array in JS. Therefore, Json also has two structures: objects and arrays. 1. Json object: Meaning: it is an unordered set format of the "'key/value' pair": The Json object is defined in the curly brackets "{}", with the Key: value key-value pairs are used to store data. Multiple key-value pairs are separated by commas (,), and multiple data are separated by semicolons. Example: {"name": "jackson", "age": 100} note: in different languages, it is understood as an object, record), structure (struct), dictionary, hash table, keyed list, or associative array ). 2. Json array: Meaning: An array is an ordered set of values. The Json array is defined in square brackets ([]) and stores data as strings, values are separated by commas (,), and multiple data are separated by semicolons. Example: Copy code 1 {2 "students": 3 [4 {"name": "jackson", "age": 100}, 5 {"name": "michael ", "age": 51} 6] 7} copy the code. Generally, we use jsp + servlet as the server side to generate Json data, and then parse Json data on the client side. To parse JSON data, you must first determine whether the JSON Object to be parsed is a JSON array, and then determine which resolution technology is used. The android platform generally has the following resolution technologies to choose from: the built-in org. json package (Json), google's open source library GSON, and some third-party open source libraries such as Jackson and FastJson. Let's take a look at how to use the open source library GSON to parse Json data. 2. The basic idea of Gson parsing Json is to first parse the Person object on the server side into a json string through Gson. Then, on the client side, use the Gson class to restore the json string to the Person object. Gson supports any complex Java objects including objects without source code. If we regard the Person object as a generic type, it can be parsed no matter what type of Person object on the server side. What is the magic about the Gson library? If a Json object is parsed, It can automatically map a Json string into an object, so that we do not need to manually write code for parsing. For example, if a piece of Json data is as follows: {"name": "tom", "age": 20}, then we can write a Person class, add the name and age fields. Simply call the following code to automatically parse the Json data into a Person object: Gson gson = new Gson (); person person = gson. fromJson (jsonData, Person. class); if you are parsing a Json object array, you need to use Typetoken (a reflection mechanism officially provided) to pass the expected data type to fromJson () the method is as follows: List <Person> people = gson. fromJson (jsonData, new TypeToken <List <Person> (). getType (); the basic usage is as follows. Let's take a look at the specific implementation steps. Iii. Gson Json parsing steps (code implementation) Now we can use an example program to explain how SAX parses XML files. This example program runs on the Android platform, to simulate the actual situation, a static XML file "person." is placed on the tomcat server. json and perons. json. The former indicates the object, and the latter indicates the object array. Create a file person in the Directory D: \ apache-tomcat-8.0.14 \ webapps \ ROOT. json and perons. json. person. the json content is as follows: {"id": 1, "name": "smyhvae", "address": "Chengdu"} note that, pay attention to the json file format. For example, do not include commas (,) at the end of line 1. (This is because of this low-level error. Later I debugged the program and called it for more than half an hour.) persons. the json content is as follows: copy the Code [{"id": 1, "name": "smyhvae", "address": "Chengdu" },{ "id": 2, "name": "Xu Ke", "address": "Hefei"}] copy the code. Note: if you are not clear about the tomcat server configuration, refer to the third section of my blog: JavaWeb Learning (1) ---- introduction to JSP and getting started (including Tomcat usage) because the IP address of my computer is 192.168.1.112. Enter http: // 192.168.1.112: 8080/person in the browser. json and http: // 192.168.1.112: 8080/persons. json. The result is as follows: the Chinese text above 62c20a5a-d316-46f8-bd1c-daf38c4e4769 contains garbled characters, but it does not matter. This will not happen when parsing later. What we need to do now is to get and parse the Json data through the Android program. Because it is an Android program, do not forget to grant it the permission to access the network. The directory structure of the entire project file is as follows: e51039d5-853b-416f-b73f-05658ead3455 (1) download and add Gson jar package: https://code.google.com/p/google-gson/ web page is as follows: 812a5333-9666-4300-ac76-e13c5a0692fe click the red box part, the following interface appears: 83df9ed0-fde0-45cb-9119-01a5682afe3d in the red box part of the gson-2.3.jar is what we need to download, if you need help documentation, you can also put the arrow at the file download. Then copy the gson-2.3.jar to the libs directory of the project file, and the Gson library is automatically added to the project. (2) [create a tool-type HttpUtils] Use URLHttpConnection to get the XML Stream on the server. The returned result is the string copy code 1 package com. example. android_gson_json.http; 2 3 import java. io. byteArrayOutputStream; 4 import java. io. IOException; 5 import java. io. inputStream; 6 import java.net. httpURLConnection; 7 import java.net. URL; 8 9 10 // get the data in the link through HttpURLCnnection, put it in the stream, and then convert the data in the stream into a string (for reference: Old Version 1-04 of Lao Luo) 11 public class HttpUtils {12 13 public HttpUtils () {14 // TODO Auto-generated constructor stub15} 16 17 public static String getJsonContent (String url_path) {18 try {19 URL url = new URL (url_path); 20 HttpURLConnection connection = (HttpURLConnection) url21. openConnection (); 22 connection. setConnectTimeout (3000); 23 connection. setRequestMethod ("GET"); 24 connection. setDoInput (true); 25 int code = connection. getResponseCode (); 26 if (code = 200) {27 return c HangeInputStream (connection. getInputStream (); 28} 29} catch (Exception e) {30 // TODO: handle exception31} 32 return ""; 33} 34 35 private static String changeInputStream (InputStream inputStream) {36 // TODO Auto-generated method stub37 String jsonString = ""; 38 ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); 39 int len = 0; 40 byte [] data = new byte [1024]; 41 try {42 while (len = InputStream. read (data ))! =-1) {43 outputStream. write (data, 0, len); 44} 45 jsonString = new String (outputStream. toByteArray (); 46} catch (IOException e) {47 // TODO Auto-generated catch block48 e. printStackTrace (); 49} 50 return jsonString; 51} 52} copy code (3) [New class Person] Create entity class Person, used to store the parsed object data copy code 1 package com. example. android_gson_json.domain; 2 3 public class Person {4 private int id; 5 private String name; 6 private Str Ing address; 7 public Person () {8 super (); 9} 10 public Person (int id, String name, String address) {11 super (); 12 this. id = id; 13 this. name = name; 14 this. address = address; 15} 16 public int getId () {17 return id; 18} 19 public void setId (int id) {20 this. id = id; 21} 22 public String getName () {23 return name; 24} 25 public void setName (String name) {26 this. name = name; 27} 28 public String getAdd Ress () {29 return address; 30} 31 public void setAddress (String address) {32 this. address = address; 33} 34 @ Override35 public String toString () {36 return "Person [id =" + id + ", name =" + name + ", address = "+ address37 +"] "; 38} 39 40} copy the code (4) [New Class GsonTools] is used to parse Json data and copy code 1 package com. example. android_gson_json.gson; 2 3 import java. util. arrayList; 4 import java. util. list; 5 6 import com. google. Gson. gson; 7 import com. google. gson. reflect. typeToken; 8 9 public class GsonTools {10 11 public GsonTools () {12 // TODO Auto-generated constructor stub13} 14 15 // use Gson to parse Person16 public static <T> T getPerson (String jsonString, Class <T> cls) {17 T = null; 18 try {19 Gson gson = new Gson (); 20 t = gson. fromJson (jsonString, cls); 21} catch (Exception e) {22 // TODO: handle exception23} 24 return T; 25} 26 27 28 // use Gson to parse the List <Person> 29 public static <T> List <T> getPersons (String jsonString, Class <T> cls) {30 List <T> list = new ArrayList <T> (); 31 try {32 Gson gson = new Gson (); 33 list = gson. fromJson (jsonString, new TypeToken <List <T> () {34 }. getType (); 35} catch (Exception e) {36} 37 return list; 38} 39 40} There are two methods on the copy code, it is used to parse the Person object and the List nested Person respectively. If there are more complex data types, let's talk about them later ~ O (distinct _ distinct) O ~ You only need to pay attention to the key ideas here. Core code: lines 19 to 20, 32 to 34 (5) instantiate in MainActicity: instantiate the link path to be accessed and parse it. The layout interface is very simple. There are only two button controls, the layout code is not displayed here. Click the button to trigger the click event. Because it is Android4.0 +, you cannot access the network in the main Thread. You need to set up another Thread. The Thread class is used here. The Code is as follows: Copy code 1 package com. example. android_gson_json; 2 3 import java. util. list; 4 5 import android. app. activity; 6 import android. OS. bundle; 7 import android. util. log; 8 import android. view. view; 9 import android. view. view. onClickListener; 10 import android. widget. button; 11 12 import com. example. android_gson_json.domain.Person; 13 import com. example. android_gson_json.gson.GsonTools; 14 import com. example. android_gson_json.http.HttpUtils; 15 16 public class MainActivity extends Activity implements OnClickListener {17 18 private Button button1, button2; 19 private static final String TAG = "MainActivity "; 20 21 @ Override22 protected void onCreate (Bundle savedInstanceState) {23 super. onCreate (savedInstanceState); 24 setContentView (R. layout. activity_main); 25 26 button1 = (Button) this. findViewById (R. id. button1); 27 button2 = (Button) this. findViewById (R. id. button2); 28 button1.setOnClickListener (this); 29 button2.setOnClickListener (this); 30} 31 32 // click the button to start parsing Json data using Gson: set of Person objects and List nested Person objects 33 @ Override34 public void onClick (final View v) {35 Thread thread = new Thread (new Runnable () {36 37 @ Override38 public void run () {39 switch (v. getId () {40 case R. id. button1: 41 String path = "http: // 192.168.1.112: 8080/person. json "; 42 String jsonString = HttpUtils. getJsonContent (path); // get data from the network 43 Person person = GsonTools. getPerson (jsonString, Person. class); // parse json Data 44 Log. I (TAG, person. toString (); 45 break; 46 case R. id. button2: 47 String path2 = "http: // 192.168.1.112: 8080/persons. json "; 48 String jsonString2 = HttpUtils. getJsonContent (path2); // obtain data from the network 49 List <Person> list = GsonTools. getPersons (jsonString2, Person. class); // parse json data 50 logs. I (TAG, list. toString (); 51 break; 52} 53 54} 55}); 56 thread. start (); 57 58} 59 60} copy the code core code: 43 lines, 49 lines (6) add network permissions: (do not forget this) <uses-sdkandroid: minSdkVersion = "14" android: targetSdkVersion = "21"/> <uses-permission android: name = "android. permission. INTERNET "/>

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.