Android Data format parsing object JSON usage

Source: Internet
Author: User

1.JSON Concept:

A lightweight data interchange format that provides good readability and quick-to-write features that enable data exchange between different platforms. JSON uses a high-compatibility text format, and also has a similar behavior to the C language system.

JSON can convert a Java object into a JSON-formatted string that converts a JSON string into Java. More lightweight than XML, JSON is lightweight and simple to use. JSON data format, which is widely used in Android for client and server communication, is very convenient for network data transmission and parsing.

2. Environment configuration

Http://code.google.com/p/google-gson/has a class library called Gson, which can be used to parse JSON data, and the Adroid 3.0 platform actually integrates this part directly into Android. We will parse the JSON data, go directly to the site to download a jar package, import into the project, you can parse the JSON data.

3.JSON applications

(1). JSON is a lightweight format for data interchange
(2). JSON is based on two types of data structures: Object and array. Where object is a collection of "name/value" pairs.

(3) contains four JSON-related classes and one exceptions in Android:

A.jsonobject

This is the basic unit in the system for JSON definition, which contains a pair of key/value values.

B.jsonarray

It represents an ordered set of values. Converts it to a string output (toString) in the form of a square bracket wrapped with a value separated by a comma "," (for example: [Value1,value2,value3]

C.jsonstringer

This class can help create jsontext quickly and easily. Its greatest advantage is that it can reduce program exceptions due to format errors, which can automatically create JSON text in strict accordance with JSON syntax rules (syntaxrules). Each Jsonstringer entity can only create one JSON text. For example:

New Jsonstringer (). Object ()   
. Key ("name")
. Value ("Piglet")
. EndObject ()

myString ={"name": "Piglet"}

D.jsontokener

This is the class for the system to parse the JSON source string for the Jsonobject and Jsonarray constructors, which can extract numeric information from the source string.

E.jsonexception

(4) JSON format example

A.object Example:

{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"URL": "http://www.example.com/image/481989943",
"Height": 125,
"Width": "100"
},
"IDs": [116, 943, 234, 38793]
}
}

B.array Example :

[
{
"Precision": "Zip",
"Latitude": 37.7668,
"Longitude":-122.3959,
"Address": " ",
"City": "SAN FRANCISCO",
"State": "CA",
"Zip": "94107",
"Country": "US"
},

{
"Precision": "Zip",
"Latitude": 37.371991,
"Longitude":-122.026020,
"Address": " ",
"City": "SUNNYVALE",
"State": "CA",
"Zip": "94085",
"Country": "US"
}
]

4.JSON Analytic case
(1) Parse one of the object:

String jsonstring ={"url": "Http://www.cnblogs.com/qianxudetianxia"};

Parsing method:

New Jsonobject (jsonstring);

String url = demojson.getstring ("url");

(2) Parse object two:

String jsonstring ={"name": "Android", "Version": "Beta1.0"};

Parsing method:

New Jsonobject (jsonstring);

String name = demojson.getstring ("name");
String Version = demojson.getstring ("version");

System.out.println ("Name:" +name+ ", Version:" +version);

(3). Parse one of the array:

String jsonString ={"number":[1,2,3]}; 解析方法:JSONObject demoJson = new JSONObject(jsonString);JSONArray numberList = demoJson.getJSONArray("number");for(int i=0; i<numberList.length(); i++){    //因为数组中的类型为int,所以为getInt,其他getString,getLong同用    System.out.println(numberList.getInt(i));}

(4). Parse the second of array:

String jsonstring ={"number": [[[1],[2],[3]]};

Parsing method:

nested arrays of group traversal
New Jsonobject (jsonstring);
Jsonarray numberlist = Demojson.getjsonarray ("number");

for (int i=0; i<numberlist.length (); i++) {
gets the array in the array
System.out.println (Numberlist.getjsonarray (i). GetInt (0));
}

(5). parsing Object and the Array:

String jsonstring ={"mobile": [{"Name": "Android"},{"name": "iphone"}]};

Parsing method:

New Jsonobject (jsonstring);
Jsonarray numberlist = Demojson.getjsonarray ("mobile");

for (int i=0; i<numberlist.length (); i++) {
System.out.println (Numberlist.getjsonobject (i). getString ("name"));
}

(6). Use Opttype:

In the above example, the use of GetType throws an exception when it encounters a node that is not found.
If a node is not found with opttype, null or default value is returned.

no URL nodes, throwing exceptions
String url = demojson.getstring ("url");

no URL node, return null, default value if basic type
String url = demojson.optstring ("url");

(7). UTF-8 BOM header causes problems parsing JSON Exceptions
When the JSON file is saved as Utf-8, the BOM header "ef BB ef" bytes are generated at the front of the text (required to be opened with 16 binary tools) under the Windows platform.
There are two ways to resolve this:
A. Use UltraEdit to open the JSON file, save as the time, choose the format UTF-8, no BOM head, if not yet, in Notepad open, save as UTF-8, try several times on it.
B. Use code processing to intercept the contents of the JSON body:

String jsonstring = getjsonstring ();

Jsonstring =jsonstring.substring (Jsonstring.indexof ("{"), Jsonstring.lastindexof ("}") +1)

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.