In android, network data transmission is often used. xml or json is usually used, while json is more lightweight, convenient, and we use more. I have used a lot in my project. Today I will talk about how to parse JSON in android, help me summarize the content, and help others avoid detours.
JSON syntax
First, let's look at the JSON syntax and structure so that we can know how to parse it. In JSON syntax, JavaScript objects represent a subset of the syntax.
The JSON value can be:
Number (integer or floating point number)
String (in double quotation marks)
Logical value (true or false)
Array (surrounded by square brackets)
Object (surrounded by curly braces)
Null
JSON has only two structures: object and array.
1. Object: Content enclosed by the object represented as "{}" in js. The data structure is{Key: value, key: value ,...}The structure of the key-value pair. In the object-oriented language, the key is the object attribute, and the value is the corresponding attribute value, so it is easy to understand that the value method is the object. key, which can be a number, String, array, or object.
2. array: The array is enclosed by [] in Javascript. The data structure is["Java", "javascript", "vb",...]The value can be obtained using indexes in the same way as in all languages. The field value type can be numbers, strings, arrays, and objects.
Andoroid parses JSON
The android sdk provides org. json for parsing json. In android3.0, json parsing and generation are performed for the android. util package JsonReader and JsonWriter.
Parse using the org. json package JSONObject and JSONArray
We know that there are two types of arrays and objects in json, so there are two classes for parsing.
For example, we have the following json strings:
{"Name": "sam", "age": 18, "weight": 60} // A json object in json1 [, 13, 15] // a number array of json2 [{"name": "sam", "age": 18 },{ "name": "leo", "age ": 19 },{ "name": "sky", "age": 20}] // The json3 json array contains objects.
Parsing of json1, the first json object
JSONObject jsonObj = new JSONObject(json1);String name = jsonObj.optString("name");int age = jsonObj.optInt("age");int weight = jsonObj.optInt("weight");
In addition
Object opt(String name)boolean optBoolean(String name)double optDouble(String name)JSONArray optJSONArray(String name)JSONObject optJSONObject(String name)
And other methods, I recommend using these methods. when parsing these methods, if the corresponding field does not exist, a null value or 0 will be returned, and no error will be reported.
Of course, if you use the following method
Object get(String name)boolean getBoolean(String name)int getInt(String name)
The Code does not determine whether the field exists. You need to determine the field by yourself. Otherwise, an error is reported. Use it if you judge it yourselfhas(String name)
.
Let's take a look at the parsed array, a simple array. Second json2
JSONArray jsonArray = new JSONArray(json2);for (int = 0; i < jsonArray.length();i++) { int age = jsonArray.optInt(i); }
Parse complex arrays, including objects, json3
JSONArray jsonArray = new JSONArray(json3);for (int = 0; i < jsonArray.length();i++) { JSONObject jsonObject = jsonArray.optJSONObject(i); String name = jsonObject.optString("name"); int age = jsonObject.optInt("age");}
From the above we can see that the array parsing method is similar to the object, but the key value is replaced with the subscript in the array. In addition, there are optXXX (int index) and getXXX (int index) methods. opt is also safe, that is, when the corresponding index has no value, no error is reported, and null is returned. We recommend that you use it.
Use JsonReader for parsing
The use of JsonReader is actually similar to the pull in xml parsing. Let's look at the example.
When JSONObject and JSONArray are created, they are transmitted as strings. When JsonReader needs to be passed in, it is a Reader. During network access, we can directly pass in the input and convert it into a Reader. Let's assume that the above String has been converted into InputStream, namely, jsonIs1, jsonIs2, and jsonIs3.
The above json1 parsing:
JsonReader reader = new JsonReader (new InputStreamReader (jsonIs1); try {points: 49 ranking: 1,495,693rd uploaded resources: 1 reader. beginObject (); while (reader. hasNext () {String keyName = reader. nextName (); if (keyName. equals ("name") {String name = reader. nextString ();} else if (keyName. equals ("age") {int age = reader. nextInt ();} else if (keyName. equals ("weight") {int weight = reader. nextInt () ;}} reader. endObject ();} finally {reader. close ();}
The above analysis of json2:
JsonReader reader = new JsonReader(new InputStreamReader(jsonIs2));try { List
ages = new ArrayList
(); reader.beginArray(); while (reader.hasNext()) { ages.add(reader.nextInt()); } reader.endArray();} finally { reader.close();}
Third, I will not write an example.
If we see this, We can traverse our json to retrieve our content. I think it will be more efficient than the first one. For specific use, we can write them out based on the two examples.
Parse JSON using GSON
GSON is produced by Google and is easy to use. At the same time, there are some other third-party such as fastjson, which are similar to Gson. Passing a string and the object to be converted will help you parse it directly, we no longer need to parse a field segment. Here we will take Gson as an example, because I have only used Gson and are most familiar with it. Pai_^
To use Gson, We need to import the Gson package, https://code.google.com/p/google-gson/downloads/list.
Now let's take a look at how to parse the above three json string examples.
First object json1
First, we need an entity class.
Public class People {public String name; @ SerializedName (age) pubic int mAge; // If the name of a Member in our class is different from the key name in the json object, you can use annotations to set the name public int weight ;}
Then you can parse it.
Gson gson = new Gson();Poeple people = gson.fromJson(json1, People.class);
For the second json2, we can resolve it to an int array or an Integer List.
Resolved to an array:
Gson gson = new Gson();int[] ages = gson.fromJson(json2, int[].class);
Resolved to List:
Gson gson = new Gson();List
ages = gson.fromJson(json2, new TypeToken
>(){}.getType);
The third one can also be resolved to a List or array, and we will directly resolve it to a List.
Gson gson = new Gson();List
peoples = gson.fromJson(json3, new TypeToke
>(){}.getType);
From the code above, Gson resolution is very simple. Note that if the corresponding key value and member name are different, you can use annotations to mark them.
Idle
As mentioned above, some mainstream resolutions are clarified. It can be seen that Gson resolution is very simple, which can save a lot of time for our development. At the same time, android itself provides enough for us, and the JsonReader operation added after 3.0 is smoother, which is similar to other methods such as Pull parsing xml.
This article only describes how to use it. Some APIs and advanced usage are not mentioned yet. After all, there is a limited description in an article. Please check the official documentation on your own.
The above is only about parsing. In fact, json generation, JSONObject, and JSONArray can all directly generate json. 3.0 also provides JsonWriter to generate json. In Gson, gson. toJson () can generate json, and everything is so wonderful. However, we usually use less to generate json, so I will not write it here (or write an article to generate it separately) ^_^.
Reference material address:
Http://developer.android.com/reference/org/json/JSONArray.html
Http://developer.android.com/reference/org/json/JSONObject.html
Http://developer.android.com/reference/android/util/JsonReader.html
Https://code.google.com/p/google-gson/
Original article address: Workshop.