JSON summary in Android

Source: Internet
Author: User

1. JSON (JavaScript ObjectNotation) Definition:
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

2. JSON structure:

(1) Name/Value Pairs (unordered): similar to the well-known Keyed list, Hash table, Disctionary, and Associative array. There is another class "Bundle" in the Android platform, which has similar behavior to some extent.

(2) Array (ordered): A list of ordered data.

Object
An object is an unordered set of Name/Value Pairs. {Name: value, name: value, name: value ....}
Example: {"name": "", "age": 20}

Array
Array is an ordered set of values. [Value, value, value...]
Value can be a string, number, true, false, null, object, or array enclosed by double quotation marks ). These structures can be nested.
A string is a collection of any number of Unicode characters enclosed by double quotes. It is escaped using a backslash. A character (character) is a separate character string (characterstring ). For example: \ + "\/B f n r t u escape.
Example 1: Array contains objects)
[{"Id": 1, "name": "", "age": 22 },{ "id": 2, "name": "kitten ", "age": 23},...]

Example 2: the same object can contain an Array

(1) An object contains an array and two child objects.
{"Root": [{"id": "001", "name": ""}, {"id": "002", "name ": "kitten" },{ "id": "003", "name": "puppy"}],
"Total": 3,
"Success": true
}

(2) the object can also be nested with sub-objects, and the sub-objects can be nested with arrays.
{"Calendar ":
{"Calendarlist ":
[
{"Id": "001", "name": ""},
{"Id": "002", "name": "kitten "}
]
}
}

In short, the formats are diverse and can be nested with each other

Android contains four JSON-related classes and one Exceptions:

JSONArray
JSONObject
JSONStringer
JSONTokener
JSONException

(1) JSONObject:

This is the basic unit related to 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 colons ). 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! "), Separate keys and values with commas.
Value types include: Boolean, JSONArray, JSONObject, Number, String, or the default Value JSONObject. NULL object.
There are two different value methods:
Get (): used when a specified value exists. Otherwise, an Exception is thrown when the Key cannot be retrieved.
Opt (): This method is relatively flexible. If the specified value cannot be obtained, a default value is returned and no exception is thrown.

(2) 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. NULLobject.

(3) JSONStringer:

According to the official explanation, this class can help you quickly and conveniently create JSONtext. 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 (syntaxrules. Each JSONStringer object can only create one JSON text.

Learn more about the following instances:

Copy codeThe Code is as follows: String myString = new JSONStringer (). object (). key ("name"). value (""). endObject (). toString ();

For a set of standard format JSON text: {"name": ""}

The. object () and. endObject () must be used at the same time to add a boundary to the value according to the Object standard. Likewise, there are a set of standard methods for arrays to generate the boundary. array () and. endArray ().

(4) JSONTokener:

This is the class in which the system parses the JSONsource string for the JSONObject and JSONArray constructors. It can extract numerical information from the source string.

JSONException:

Is the exception information thrown by the JSON.org class.
A complete application instance is referenced below:
Use JSONObject to store Map-type values:Copy codeThe Code is as follows: public static JSONObject getJSON (Map map ){
Iterator iter = map. entrySet (). iterator ();
JSONObject holder = new JSONObject ();
While (iter. hasNext ()){
Map. Entry pairs = (Map. Entry) iter. next ();
String key = (String) pairs. getKey ();
Map m = (Map) pairs. getValue ();
JSONObject data = new JSONObject ();
Try {
Iterator iter2 = m. entrySet (). iterator ();
While (iter2.hasNext ()){
Map. Entry pairs2 = (Map. Entry) iter2.next ();
Data. put (String) pairs2.getKey (), (String) pairs2
. GetValue ());
}
Holder. put (key, data );
} Catch (JSONException e ){
Log. e ("Transforming", "There was an error packaging JSON", e );
}
}
Return holder;
}

The following is a detailed example:Copy codeThe Code is as follows: import java. io. ByteArrayOutputStream;
Import java. io. InputStream;
Import java.net .*;
Import java. util. ArrayList;
Import java. util. HashMap;
Import java. util. List;
Import java. util. Map;
Import org. json. JSONArray;
Import org. json. JSONObject;
Import android. util. Log;

Public class JSON {

/**
* Get JSON data in the "array form,
* Data Format: [{"id": 1, "name": "" },{ "id": 2, "name": "kitten"}]
* @ Param path: webpage path
* @ Return returns List
* @ Throws Exception
*/
Public static List <Map <String, String> getJSONArray (String path) throws Exception {
String json = null;
List <Map <String, String> list = new ArrayList <Map <String, String> ();
Map <String, String> map = null;
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // use the HttpURLConnection object to obtain webpage data from the network.
Conn. setConnectTimeout (5*1000); // The unit is milliseconds and the timeout value is set to 5 seconds.
Conn. setRequestMethod ("GET"); // HttpURLConnection requests the path through the HTTP protocol. Therefore, you need to set the request method. You can leave it unspecified because the default value is GET.
If (conn. getResponseCode () = 200) {// check whether the request code is 200; otherwise, the request fails.
InputStream is = conn. getInputStream (); // gets the input stream
Byte [] data = readStream (is); // converts the input stream to a character array
Json = new String (data); // converts a character array to a String

// Data format: [{"id": 1, "name": "", "age": 22 },{ "id": 2, "name ": "kitten", "age": 23}]
JSONArray jsonArray = new JSONArray (json); // data is directly in the form of an Array. Therefore, you can directly use the JSONArray framework provided by android to read JSON data and convert it to an Array.

For (int I = 0; I <jsonArray. length (); I ++ ){
JSONObject item = jsonArray. getJSONObject (I); // each record is composed of several Object objects.
Int id = item. getInt ("id"); // obtain the value of the object
String name = item. getString ("name ");

Map = new HashMap <String, String> (); // store it in MAP.
Map. put ("id", id + "");
Map. put ("name", name );
List. add (map );
}
}

******************
For (Map <String, String> list2: list ){
String id = list2.get ("id ");
String name = list2.get ("name ");
Log. I ("abc", "id:" + id + "| name:" + name );
}
Return list;
}

/**
* Obtain JSON data of "object form,
* Data Format: {"total": 2, "success": true, "arrayData": [{"id": 1, "name": ""}, {"id": 2, "name": "kitten"}]}
* @ Param path: webpage path
* @ Return returns List
* @ Throws Exception
*/
Public static List <Map <String, String> getJSONObject (String path) throws Exception {
List <Map <String, String> list = new ArrayList <Map <String, String> ();
Map <String, String> map = null;
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // use the HttpURLConnection object to obtain webpage data from the network.
Conn. setConnectTimeout (5*1000); // The unit is milliseconds and the timeout value is set to 5 seconds.
Conn. setRequestMethod ("GET"); // HttpURLConnection requests the path through the HTTP protocol. Therefore, you need to set the request method. You can leave it unspecified because the default value is GET.
If (conn. getResponseCode () = 200) {// check whether the request code is 200; otherwise, the request fails.
InputStream is = conn. getInputStream (); // gets the input stream
Byte [] data = readStream (is); // converts the input stream to a character array
String json = new String (data); // converts a character array to a String

// Data format: {"total": 2, "success": true, "arrayData": [{"id": 1, "name": ""}, {"id": 2, "name": "kitten"}]}
JSONObject jsonObject = new JSONObject (json); // The returned data is of the Object type, so it can be directly converted into an Object.
Int total = jsonObject. getInt ("total ");
Boolean success = jsonObject. getBoolean ("success ");
Log. I ("abc", "total:" + total + "| success:" + success); // Test Data

JSONArray jsonArray = jsonObject. getJSONArray ("arrayData"); // contains an array of data, which can be obtained using getJSONArray.
For (int I = 0; I <jsonArray. length (); I ++ ){
JSONObject item = jsonArray. getJSONObject (I); // obtain each object
Int id = item. getInt ("id"); // obtain the value of the object
String name = item. getString ("name ");

Map = new HashMap <String, String> (); // store it in MAP.
Map. put ("id", id + "");
Map. put ("name", name );
List. add (map );
}
}

******************

For (Map <String, String> list2: list ){
String id = list2.get ("id ");
String name = list2.get ("name ");
Log. I ("abc", "id:" + id + "| name:" + name );
}
Return list;
}

/**
* Obtain complex JSON Data Types
* Data Format:
{"Name": "pig ",
"Age": 23,
"Content": {"questionsTotal": 2,
"Questions": [{"question": "what's your name? "," Answer ":" "},{" question ":" what's your age "," answer ":" 23 "}]
}
}
* @ Param path: webpage path
* @ Return returns List
* @ Throws Exception
*/
Public static List <Map <String, String> getJSON (String path) throws Exception {
List <Map <String, String> list = new ArrayList <Map <String, String> ();
Map <String, String> map = null;
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // use the HttpURLConnection object to obtain webpage data from the network.
Conn. setConnectTimeout (5*1000); // The unit is milliseconds and the timeout value is set to 5 seconds.
Conn. setRequestMethod ("GET"); // HttpURLConnection requests the path through the HTTP protocol. Therefore, you need to set the request method. You can leave it unspecified because the default value is GET.
If (conn. getResponseCode () = 200) {// check whether the request code is 200; otherwise, the request fails.
InputStream is = conn. getInputStream (); // gets the input stream
Byte [] data = readStream (is); // converts the input stream to a character array
String json = new String (data); // converts a character array to a String

/* Data format:
{"Name": "pig ",
"Age": 23,
"Content": {"questionsTotal": 2,
"Questions": [{"question": "what's your name? "," Answer ":" "},{" question ":" what's your age "," answer ":" 23 "}]
}
}
*/
JSONObject jsonObject = new JSONObject (json); // The returned data is of the Object type, so it can be directly converted into an Object.
String name = jsonObject. getString ("name ");
Int age = jsonObject. getInt ("age ");
Log. I ("abc", "name:" + name + "| age:" + age); // Test Data

JSONObject contentObject = jsonObject. getJSONObject ("content"); // get the object in the object
String questionsTotal = contentObject. getString ("questionsTotal"); // obtain a value in the object
Log. I ("abc", "questionsTotal:" + questionsTotal); // Test Data

JSONArray contentArray = contentObject. getJSONArray ("questions"); // obtain the array in the object
For (int I = 0; I <contentArray. length (); I ++ ){
JSONObject item = contentArray. getJSONObject (I); // obtain each object
String question = item. getString ("question"); // obtain the value of the object
String answer = item. getString ("answer ");

Map = new HashMap <String, String> (); // store it in MAP.
Map. put ("question", question );
Map. put ("answer", answer );
List. add (map );
}
}

******************

For (Map <String, String> list2: list ){
String question = list2.get ("question ");
String answer = list2.get ("answer ");
Log. I ("abc", "question:" + question + "| answer:" + answer );
}
Return list;
}

/**
* Convert the input stream to a character array
* @ Param inputStream input stream
* @ Return character array
* @ Throws Exception
*/
Public static byte [] readStream (InputStream inputStream) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Int len = 0;
While (len = inputStream. read (buffer ))! =-1 ){
Bout. write (buffer, 0, len );
}
Bout. close ();
InputStream. close ();

Return bout. toByteArray ();
}
}

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.