"Android Development experience" JSON data format introduction, using the Android self-brought class library to complete the JSON generation and parsing

Source: Internet
Author: User
Tags tojson

Reprint Please specify Source: http://blog.csdn.net/zhaokaiqiang1992

Because both XML and JSON data formats have been used in previous projects, they are impressive in the simple, efficient nature of JSON format. JSON data format is highly recommended if you are developing with the JSON language!

JSON (JavaScript Object Notation) is a lightweight data interchange format. Easy for people to read and write.  It is also easy for machine parsing and generation. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.


JSON is constructed in two structures:
(1) A collection of "name/value" pairs (A collection of name/value pairs). In different languages, it is understood as objects (object), record (record), structure (struct), Dictionary (dictionary), hash table (hash table), keyed list (keyed list), or associative array (associative Array).
(2) An ordered list of values (an ordered list of values). In most languages, it is understood as an array (array).

Because this kind of data structure exists in some form in most modern computer languages. Therefore, it is possible for a data format to be exchanged between programming languages that are also based on these constructs. For example, when writing API interfaces to Android and iOS, cross-platform support can be implemented in JSON format.


1. Key-value pair form:

In this way we can correspond to the map structure in Java. An object starts with "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).

Here is a simple example of the form of a key-value pair:

{
"Name": "Zhao",
"Age": 22,
"Address": "Qingdao"
}

The preceding key is a string string, but the following values can be of several types, such as strings, bool, numeric values, null, objects, or even arrays.

Here is a simple example of a value that is an object:

{
"Name": "Zhao",
"Age": 22,
"Address": "Qingdao",
"Birthday": {
"Year": 19,
"Month": 1,
"Day": 19
}
}

We can use the figure below to represent this form



2. Array form

An array is an ordered collection of values (value). An array begins with "[" (the left square bracket), and "]" (the right square bracket) ends. Use "," (comma) to separate values.

For classes in Java, we can think of this as an array of objects that can be placed in double quotation marks (string), value (number), True, false, NULL, object, or array. These structures can be nested.

The following is an example of using an array form:

[
"Zhaokaiqiang",
22,
"Qingdao",
{
"Year": 1992,
"Month": 1,
"Day": 19
},
True
Null
]

We can use the figure below to represent this form



Value can be represented using the following image.



If there are characters in the string that need to be escaped, refer to the following description of escape



JSON data format that's a little bit of stuff, very simple and straightforward. The class inside the Org.json package that comes with Android can generate JSON-formatted data or parse the data in JSON format.

The following is a brief introduction to the use of JSON-related classes in Android, but it is strongly not recommended that you use the JSON-related class of Android!

There are 5 classes related to JSON, and the following are some examples of how to use these classes



1.JSONObject

This class mainly encapsulates the data manipulation of JSON key-value pairs, and the following are some common methods:

Jsonobject.put (key,values);//Add to generate JSON

Jsonobject.get (key);//get, used to parse JSON

Jsonobject.optxxx (key);//is also used for fetching, which is used when parsing, but does not throw an exception, but instead returns the default value

If we are going to generate a string in the form of a key-value pair, you can use this class, just like the following code

public void Objecttojson () throws Exception {Jsonobject jsonobject = new Jsonobject (); Jsonobject.put ("Name", " Zhaokaiqiang "); Jsonobject.put (" Age ", 22); LOG.D (TAG, jsonobject.tostring ());}

The results are as follows:

{"Age": $, "name": "Zhaokaiqiang"}

Because there is no way to directly convert, so it is only possible to set the key and value itself, very troublesome.


2.JSONArray

This class is primarily encapsulated in an ordered array of operations. Common methods are similar to Jsonobject:

Jsonarray.put (key,values);//Add to generate JSON

Jsonarray.get (key);//get, used to parse JSON

Jsonarray.optxxx (key);//is also used for fetching, which is used when parsing, but does not throw an exception, but instead returns the default value

Here is a small example to use:

public void Objecttojson () throws Exception {Jsonarray Jsonarray = new Jsonarray (); Person p = new person ("Zhaokaiqiang", New Birthday (1992, 1, +)), Jsonarray.put ("ToJson"); jsonarray.put (100); Jsonarray.put (True); Jsonarray.put (P); LOG.D (TAG, jsonarray.tostring ());}

Here are the test results:

["ToJson", 100,true, "person [Name=zhaokaiqiang, age=22, Birthday=birthday [year=1992, Month=1, day=19]]"
When we add objects in the Jsonarray, we actually insert the string of the object's ToString () method into it, which is very inconvenient for us to deserialize, which is why I don't recommend this class.


3.JSONStringer

This class is used to facilitate the construction of JSON-formatted strings. The following are common methods:

Jsonstringer.object ();//Start building a JSON for the form of a key-value pair

Jsonstringer.key (name);//Add a key

Jsonstringer.values (value);//Add Value

Jsonstringer.endobject ();//The construction of JSON in the form of end key-value pairs

Of course, it can also be constructed in the form of arrays, are the same usage, but explained more, here is a simple example

public void Jsonstringertojson () throws Exception {Jsonstringer Jsonstringer = new Jsonstringer (); Jsonstringer.object () ; Jsonstringer.key ("name"); Jsonstringer.value ("Zhaokaiqiang"); Jsonstringer.key ("Age"); Jsonstringer.value (22); Jsonstringer.key ("Birthday"); Jsonstringer.value (New Birthday (1992, 1, +)); Jsonstringer.endobject (); LOG.D (TAG, jsonstringer.tostring ());}

Here are the output results

{"Name": "Zhaokaiqiang", "Age": "Birthday": "Birthday [year=1992, Month=1, day=19]"}

If you want to generate JSON in the form of an array, simply change the object to an array.


4.JSONTokener

This class is used to parse the JSON text, which is relatively weak.

Here is a sample code directly below:

public void Fromjson () throws Exception {Jsonstringer Jsonstringer = new Jsonstringer (); Jsonstringer.object (); Jsonstringer.key ("name"); Jsonstringer.value ("Zhaokaiqiang"); Jsonstringer.key ("Age"); Jsonstringer.value (22); Jsonstringer.endobject (); String jsonstring = jsonstringer.tostring (); LOG.D (TAG, "generated JSON----------" + jsonstring); Jsontokener Jsontokener = new Jsontokener (jsonstring); Jsonobject Jsonobject = (jsonobject) jsontokener.nextvalue (); String name = jsonobject.getstring ("name"); int = Jsonobject.getint ("Age"); LOG.D (TAG, "name=" + name); LOG.D (TAG, "age=" + Age);}

Here are the output results

11-26 14:15:37.842:d/jsontest (10053): Generated JSON----------{"name": "Zhaokaiqiang", "Age": 22}11-26 14:15:37.842:d/ Jsontest (10053): name=zhaokaiqiang11-26 14:15:37.842:d/jsontest (10053): age=22

5.JSONException

This is an error in our parsing process, for example, if you want to do this, you will throw an exception

Jsonobject.getstring ("Age");

This error occurs because the "age" corresponds to a field that is of type int and if read by string.


The last word: because the JSON-related class features of Android are too weak, it is strongly deprecated! These things to know can be prevented from looking at other people's code to meet the understanding. In the following article I will introduce the better, more efficient JSON data format parsing and generation, such as Google's Gson, please look forward to.

"Android Development experience" JSON data format introduction, using the Android self-brought class library to complete the JSON generation and parsing

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.