1. JSON (JavaScript objectnotation) Definition:
A lightweight data interchange format with good readability and fast-coding features. The industry's mainstream technology provides it with a complete solution (a bit like regular expressions that are supported by most languages today), allowing data exchange between platforms. JSON uses a highly compatible text format, as well as behavior similar to the C language system. –json.org
2, the structure of JSON:
(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 that has similar behavior in some ways.
(2) Array (ordered): A set of ordered list of data.
Object
The object is a unordered name/value pairs collection. {name:value, Name:value, Name:value ...}
Example: {"name": "Piggy", "Age": 20}
Array
An array is an ordered collection of values (value). [Value, value, value ...]
Values (value) can be enclosed in double quotes (string), numeric (number), True, False, NULL, objects (object), or arrays (array). These structures can be nested.
A string is a collection of any number of Unicode characters enclosed by double quotes, which is escaped using backslashes. A character (character) is a separate string (characterstring). For example: \ + "\/b f n r t U for Escape."
Example 1:array inside contains objects (object)
[{"id": 1, "name": "Piggy", "Age":}, {"id": 2, "name": "Kitten", "Age": 23}, ...]
Example 2: An array can be included in the same object
(1) An object contains 1 arrays, 2 child objects
{"Root": [{"id": "001", "Name": "Piggy"},{"id": "002", "name": "Kitten"},{"id": "003", "name": "Puppy"}],
"Total": 3,
' Success ': true
}
(2) can also object nested child objects, sub objects nested arrays
{"Calendar":
{"Calendarlist":
[
{"id": "001", "Name": "Piggy"},
{"id": "002", "name": "Kitten"}
]
}
}
In short, the format is diverse and can be nested
contains four JSON-related classes and a exceptions in Android:
Jsonarray
Jsonobject
Jsonstringer
Jsontokener
Jsonexception
(1) Jsonobject:
This is the basic unit of the system for the JSON definition, which contains a pair of key/value values.
Its response to an external (External: The value of the output of the application ToString () method) is reflected as a standard string (for example: {"JSON": "Hello, World"}, wrapped in curly braces, where key and value are separated by a colon ":"). It has a slight operational format for internal (Internal) behavior, such as initializing a Jsonobject instance, and referencing the internal put () method to add a value: New Jsonobject (). Put ("JSON", "Hello, world!"), The key and value are separated by commas ",".
The types of value include: Boolean, Jsonarray, Jsonobject, number, string, or Default value Jsonobject.null object.
There are two different methods of taking values:
Get (): used under conditions that determine the existence of a value, or a exception message will be thrown if the associated key cannot be retrieved.
Opt (): This method is relatively flexible and will return a default value when the specified value cannot be obtained, and will not throw an exception.
(2) Jsonarray:
It represents a set of ordered values. The form of converting it to string output (toString) is wrapped in square brackets, with values separated by commas "," (for example, [Value1,value2,value3], where you can use the short code to get a more intuitive understanding of its format). The interior of this class also has query behavior, and both the Get () and opt () methods can return the specified value through the index index, and the put () method is used to add or replace the numeric value.
The value type of the same class can include Boolean, Jsonarray, Jsonobject, number, string, or default value Jsonobject.nullobject.
(3) Jsonstringer:
According to the official explanation, this class can help to create jsontext quickly and easily. The biggest advantage of this is that you can reduce the error in the format resulting in a program exception, referencing this class can automatically create JSON text strictly according to the JSON syntax rules (syntaxrules). Only one JSON text can be created for each Jsonstringer entity.
Follow the example below to find out about other information:
Copy Code code as follows:
String myString = new Jsonstringer (). Object (). Key ("name"). Value ("Piggy"). EndObject (). toString ();
If it is a standard set of JSON text:{"name": "Piggy"}
The. Object () and. EndObject () must be used at the same time to add boundaries to the values according to the object criteria. Similarly, there is a standard set of methods for arrays to generate boundaries. Array () and. Endarray ().
(4) Jsontokener:
This is a class in which the system resolves the jsonsource string for the Jsonobject and Jsonarray constructors, and it can extract numeric information from the source string.
Jsonexception:
Is the exception information thrown by the Json.org class.
The following refers to a complete application instance:
Apply Jsonobject to store map type values:
Copy Code code 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 is an error packaging JSON", e);
}
}
return holder;
}
The following is a detailed example:
Copy Code code 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 {
/**
* Gets the JSON data for "array form",
* Data form: [{"id": 1, "name": "Piggy"},{"id": 2, "name": "Kitten"}]
* @param path Web page
* @return Return 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 ()//using the HttpURLConnection object, we can get the Web page data from the network.
Conn.setconnecttimeout (5 * 1000); Unit is milliseconds, set timeout time to 5 seconds
Conn.setrequestmethod ("get"); HttpURLConnection requests the path path through the HTTP protocol, so you need to set the request mode, and you can not set it, because the default is get
if (conn.getresponsecode () = = 200) {//Determine if the request code is 200 yards, or fail
InputStream is = Conn.getinputstream (); Get input stream
byte[] data = Readstream (IS); Change input flow to character array
JSON = new String (data); Converts a character array to a string
Data form: [{"id": 1, "name": "Piggy", "Age": 22},{"id": 2, "name": "Kitten", "Age": 23}]
Jsonarray Jsonarray = new Jsonarray (JSON); The data is directly an array, so you can read the JSON data directly with the framework provided by Android and convert it to an array jsonarray
for (int i = 0; i < jsonarray.length (); i++) {
Jsonobject item = jsonarray.getjsonobject (i); Each record is made up of several object objects
int id = item.getint ("id"); Gets the corresponding value of the object
String name = item.getstring ("name");
Map = new hashmap<string, string> (); stored in Map
Map.put ("id", ID + "");
Map.put ("name", name);
List.add (map);
}
}
Test Data ******************
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;
}
/**
* Get JSON data for "object form",
* Data form: {"Total": 2, "Success": true, "Arraydata": [{"id": 1, "name": "Piggy"},{"id": 2, "name": "Kitten"}]}
* @param path Web page
* @return Return 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 ()//using the HttpURLConnection object, we can get the Web page data from the network.
Conn.setconnecttimeout (5 * 1000); Unit is milliseconds, set timeout time to 5 seconds
Conn.setrequestmethod ("get"); HttpURLConnection requests the path path through the HTTP protocol, so you need to set the request mode, and you can not set it, because the default is get
if (conn.getresponsecode () = = 200) {//Determine if the request code is 200 yards, or fail
InputStream is = Conn.getinputstream (); Get input stream
byte[] data = Readstream (IS); Change input flow to character array
String json = new string (data); Converts a character array to a string
Data form: {"Total": 2, "Success": true, "Arraydata": [{"id": 1, "name": "Piggy"},{"id": 2, "name": "Kitten"}]}
Jsonobject jsonobject=new Jsonobject (JSON); The returned data form is an object type, so it can be converted directly 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");//Inside there is an array of data, you can use Getjsonarray to get the array
for (int i = 0; i < jsonarray.length (); i++) {
Jsonobject item = jsonarray.getjsonobject (i); Get each object
int id = item.getint ("id"); Gets the corresponding value of the object
String name = item.getstring ("name");
Map = new hashmap<string, string> (); stored in Map
Map.put ("id", ID + "");
Map.put ("name", name);
List.add (map);
}
}
Test Data ******************
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;
}
/**
* Get type of complex JSON data
* Data form:
{"Name": "Piggy",
"Age": 23,
"Content": {"Questionstotal": 2,
"Questions": [{"Question": "What ' s Your name", "Answer": "Piggy"},{"question": "What ' Your Age", "answer": "23"}]
}
}
* @param path Web page
* @return Return 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 ()//using the HttpURLConnection object, we can get the Web page data from the network.
Conn.setconnecttimeout (5 * 1000); Unit is milliseconds, set timeout time to 5 seconds
Conn.setrequestmethod ("get"); HttpURLConnection requests the path path through the HTTP protocol, so you need to set the request mode, and you can not set it, because the default is get
if (conn.getresponsecode () = = 200) {//Determine if the request code is 200 yards, or fail
InputStream is = Conn.getinputstream (); Get input stream
byte[] data = Readstream (IS); Change input flow to character array
String json = new string (data); Converts a character array to a string
/* Data form:
{"Name": "Piggy",
"Age": 23,
"Content": {"Questionstotal": 2,
"Questions": [{"Question": "What ' s Your name", "Answer": "Piggy"},{"question": "What ' Your Age", "answer": "23"}]
}
}
*/
Jsonobject jsonobject=new Jsonobject (JSON); The returned data form is an object type, so it can be converted directly 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"); Getting objects in an object
String questionstotal=contentobject.getstring ("Questionstotal"); Gets a value in the object
LOG.I ("abc", "Questionstotal:" + questionstotal); Test data
Jsonarray Contentarray=contentobject.getjsonarray ("questions"); Get an array in an object
for (int i = 0; i < contentarray.length (); i++) {
Jsonobject item = contentarray.getjsonobject (i); Get each object
String question = item.getstring ("question"); Gets the corresponding value of the object
String answer = item.getstring ("answer");
Map = new hashmap<string, string> (); stored in Map
Map.put ("question", question);
Map.put ("answer", answer);
List.add (map);
}
}
Test Data ******************
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 input flow to 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 ();
}
}