Android Json and androidjson
Json: a lightweight data exchange format with good readability and ease of writing. Mainstream technologies in the industry provide a complete solution (similar to regular expressions and supported by most languages) to exchange data between different platforms. JSON adopts a highly compatible text format and has behaviors similar to the C language system. -Json.org
Official website address: http://www.json.org/
JSON Vs XML
1. The data readability of JSON and XML is basically the same.
2. JSON and XML have the same rich parsing Methods
3. JSON is smaller than XML.
4. easier interaction between JSON and JavaScript
5. JSON is less descriptive than XML.
6. JSON is much faster than XML.
I. JSON syntax
JSON syntax rules
- Data in name/value pairs
- Data is separated by commas (,).
- Brackets save objects
- Square brackets Save the Array
JSON name/value pair
JSON data is written in the format of name/value pair.
Name/value pair includes the field name (in double quotation marks), followed by a colon, followed by a value:
"firstName" : "John"
JSON Value
The JSON value can be:
- Number (integer or floating point number)
- String (in double quotation marks)
- Logical value (true or false)
- Array (in square brackets)
- Object (in curly brackets)
- Null
- JSONObject
- JSONArray
JSON object
JSON objects are written in curly brackets:
The object can contain multiple name/value pairs:
{ "firstName":"John" , "lastName":"Doe" }
One {} is a JSONObject.JSON Array
JSON array is written in square brackets:
An array can contain multiple objects:
{"employees": [{ "firstName":"John" , "lastName":"Doe" },{ "firstName":"Anna" , "lastName":"Smith" },{ "firstName":"Peter" , "lastName":"Jones" }]}
In the preceding example, the object "employees" is an array containing three objects. Each object represents a record about someone (with a surname and a name.
Ii. json parsing class provided by android
The json parsing section of android is in the org. json package, which mainly includes the following classes:
JSONObject: it can be viewed as a json object, which is the basic unit of the JSON definition in the system. It contains a pair of Key/Value values. Its response to an External call (External: Applying the value output by the toString () method) is a standard string (for example, {"JSON": "Hello, World "}, the outmost is enclosed by braces, and the Key and Value are separated by the colon ). The operation format for Internal (Internal) behaviors is slightly. For example, to initialize a JSONObject instance, reference the Internal put () method to add a value: new JSONObject (). put ("JSON", "Hello, World! "), Separated by commas (,) between keys and values. Value types include Boolean, JSONArray, JSONObject, Number, String, or JSONObject. NULLobject by default.
JSONStringer: json text Build class. According to official explanations, this class can help you quickly and conveniently create JSON text. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON text in strict accordance with the JSON syntax rules (syntax rules. Each JSONStringer object can only create one JSON text.
JSONArray: it represents a group of ordered values. The format of toString output is enclosed in square brackets. Values are separated by commas (,) ([value1, value2, value3], you can use the short code to learn more about the format ). This class has the same internal query behavior. The get () and opt () methods can both return the specified value through the index, and the put () method is used to add or replace the value. The value Type of this class can also include: Boolean, JSONArray, JSONObject, Number, String, or the default value JSONObject. NULL object.
JSONTokener: json parsing class
JSONException: Exceptions in json
1. parse JSONObject and JSONArray to create Json
Sample Code:
/* json:{ "languages":[ {"id":1,"ide":"Eclispe","name":"java"}, {"id":2,"ide":"Xcode","name":"Swift"}, {"id":3,"ide":"Visual Studio","name":"C++"}], "cat":{"cat":"miao"} }*/public void creatJson2(){try {JSONObject root = new JSONObject();JSONObject cat = new JSONObject();cat.put("cat", "miao");JSONArray array = new JSONArray();JSONObject lan1 = new JSONObject();lan1.put("id", 1).put("ide", "Eclispe").put("name", "java");JSONObject lan2 = new JSONObject();lan2.put("id", 2).put("ide", "Xcode").put("name", "Swift");JSONObject lan3 = new JSONObject();lan3.put("id", 3).put("ide", "Visual Studio").put("name", "C++");array.put(lan1);array.put(lan2);array.put(lan3);root.put("languages", array);root.put("cat", cat);System.out.println("json:"+root.toString());} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
The parsed code is as follows:
public void parseJson(){try {InputStreamReader is = new InputStreamReader(getAssets().open("test2.json"), "UTF-8");BufferedReader br = new BufferedReader(is);String line;StringBuilder builder = new StringBuilder();while((line=br.readLine())!=null){builder.append(line);}is.close();br.close(); JSONObject root = new JSONObject(builder.toString()); System.out.println("cat:"+root.getString("cat")); JSONArray array = root.getJSONArray("languages"); for(int i=0;i<array.length();i++){ JSONObject lan = array.getJSONObject(i); System.out.println(".........."); System.out.println("id="+lan.getInt("id")); System.out.println("ide="+lan.getString("ide")); System.out.println("name="+lan.getString("name")); } } catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}The source file to be parsed:
{ "languages":[ {"id":1,"ide":"Eclipse","name":"java"}, {"id":2,"ide":"Xcode","name":"Swift"}, {"id":3,"ide":"Visual Studio","name":"C++"} ], "cat":"miao"}
2. JSONStringer generates json
Stringers only encode well-formed JSON strings. In particle:
- The stringer must have exactly one top-level array or object.
- Lexical scopes must be balanced: every call
array()Must have a matching callendArray()And every callobject()Must have a matching callendObject(). // Each time array () is called, The endArray, object, and endObject must be matched.
- Arrays may not contain keys (property names ).
- Objects must alternate keys (property names) and values.
- Values are inserted with either literal
valueCILS, or by nesting arrays or objects.
It defines all the methods:
| Public Constructors |
| |
JSONStringer () |
| Public Methods |
| JSONStringer |
Array () Begins encoding a new array. |
| JSONStringer |
EndArray () Ends encoding the current array. |
| JSONStringer |
EndObject () Ends encoding the current object. |
| JSONStringer |
Key (String name) Encodes the key (property name) to this stringer. |
| JSONStringer |
Object () Begins encoding a new object. |
| String |
ToString () Returns the encoded JSON string. |
| JSONStringer |
Value (double value) EncodesvalueTo this stringer. |
| JSONStringer |
Value (Object value) Encodesvalue. |
| JSONStringer |
Value (long value) EncodesvalueTo this stringer. |
| JSONStringer |
Value (boolean value) EncodesvalueTo this stringer. |
It does not have many methods, so it is very simple to use Stringer to create json.
Sample Code:
/* Json: {"Ages": [{"id": 1, "ide": "Eclispe", "name": "java" },{ "id ": 2, "ide": "Xcode", "name": "Swift" },{ "id": 3, "ide": "Visual Studio", "name ": "C ++"}], "cat": {"name": "miao"} */public String createJson () {JSONStringer stringer = new JSONStringer (); // every call to array () must have a matching call to endArray () and // every call to object () must have a matching call to endObject (). try {stringer. object (); stringer. key ("Ages"); stringer. array (); // three objects in the array stringer. object (); stringer. key ("id "). value (1 ). key ("ide "). value ("Eclispe "). key ("name "). value ("java"); stringer. endObject (); stringer. object (); stringer. key ("id "). value (2 ). key ("ide "). value ("Xcode "). key ("name "). value ("Swift"); stringer. endObject (); stringer. object (); stringer. key ("id "). value (3 ). key ("ide "). value ("Visual Studio "). key ("name "). value ("C ++"); stringer. endObject (); stringer. endArray (); // The End of the array stringer. key ("cat"); stringer. object (); stringer. key ("name "). value ("miao "). endObject (); // end objectstringer. endObject (); System. out. println ("json:" + stringer. toString ();} catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return stringer. toString ();}
Please indicate the source of forwarding: http://blog.csdn.net/jycboy
A good blog post, introduced a lot of Methods: http://www.open-open.com/lib/view/open1326376799874.html
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.