Detailed summary of JSON in Android

  • 2020-05-09 19:15:14
  • OfStack

1. Definition of JSON(JavaScript ObjectNotation) :
A lightweight data interchange format that is readable and easy to write quickly. Mainstream technologies provide a complete solution (somewhat like regular expressions, supported by most of today's languages) for data exchange between platforms. JSON USES a highly compatible text format, but also behaves in a way that is similar to the C language. � Json org

2. Structure of JSON:

(1) Name/Value Pairs (disordered) : similar to the familiar Keyed list, Hash table, Disctionary and Associative array. In the Android platform, there is another class "Bundle", which has similar behavior to some extent.

(2) Array (ordered) : 1 set of ordered data list.

object
The object is an unordered collection of Name/Value Pairs. {name:value, name:value, name:value... }
Example: {"name":" piglet ","age":20}

Array
Array is an ordered set of values (value). [value, value, value...]
The value (value) can be a double quoted string (string), a numeric value (number), an true, false, null, an object (object), or an array (array). These structures can be nested.
A string (string) is a collection of any number of Unicode characters surrounded by double quotes, escaped using a backslash. 1 character (character) is a single string (characterstring). For example: \ + "\/ b f n r t u escape.
Example 1: Array contains objects (object)
[{" id ": 1," name ":" pig ", "age" : 22}, {" id ": 2," name ":" cat ", "] age ": 23},...

Example 2: Array can be included in the same object (object)

(1) 1 object contains 1 array and 2 child objects
{" root ": [{" id" : "001", "name" : "pig"}, {" id ":" 002 ", "name" : "kitten"}, {" id ":" 003 ", "name" : "the dog"}].
"total":3,
"success":true
}

(2) objects can also nest subobjects, which then nest arrays
{"calendar":
{"calendarlist":
[
{" id ":" 001 ", "name" : "pig"},
{" id ":" 002 ", "name" : "kitten"}
]
}
}

In short, the formats are varied and can be nested within each other

Android contains four JSON related classes and one Exceptions:

JSONArray
JSONObject
JSONStringer
JSONTokener
JSONException

(1) JSONObject:

This is the base unit of the system definition of JSON, which contains a pair of values (Key/Value).
Its response to the external (External: the value output by the toString() method) call is represented as a standard string (e.g., {" JSON ":" Hello, World "}, surrounded by curly braces, where Key and Value are separated by a colon ":"). Its operation format for the internal (Internal) behavior is slightly, for example: initialize an instance of JSONObject, and add a value by referring to the internal put() method: new JSONObject().put(" JSON ", "Hello, World!") ), separated by a comma ", "between Key and Value.
The types of Value include: Boolean, JSONArray, JSONObject, Number, String, or the default JSONObject.NULL object.
There are two different ways:
get(): used in the condition that the value exists, otherwise when the relevant Key cannot be retrieved, an Exception message will be thrown.
opt(): this method is relatively flexible. When the specified value cannot be obtained, a default value will be returned without throwing an exception.

(2) JSONArray:

It represents an ordered set of values. Converts it to String output (toString) is in the form of exhibit with square brackets, value with a comma ", "space (for example: [value1 value2, value3], you can use more intuitive understanding of the short code format). This class also has query behavior inside, get() and opt() both methods can return specified values through the index index, and put() is used to add or replace values.
Again, the value type of this class can include: Boolean, JSONArray, JSONObject, Number, String, or the default JSONObject.NULLobject.

(3) JSONStringer:

According to the official explanation, this class helps to create JSONtext quickly and easily. Its biggest advantage is that it can reduce the number of program exceptions due to formatting errors. The reference to this class can automatically create JSON text strictly according to JSON grammar rules (syntaxrules). Only one JSON text can be created for each JSONStringer entity.

See the following example for other relevant information:

 
String myString = new JSONStringer().object().key("name").value(" The pig ").endObject().toString(); 


If 1 set of standard JSON text: {"name" :" piglet "}

The.object() and.endObject() must be used together in order to add a boundary to the value according to the Object standard. Also, there is a standard set of methods for generating bounds.array () and.endArray () for arrays.

(4) JSONTokener:

This is the class that the system parses JSONsource string for the JSONObject and JSONArray constructors, which can extract numeric information from source string.

JSONException:

Is the exception information thrown by the JSON.org class.
Here is a reference to a complete application example:
Use JSONObject to store values of type Map:
 
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; 
} 

Here's a detailed example:
 
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 { 

/** 
*  To obtain " An array " the JSON The data,  
*  Data form: [{"id":1,"name":" The pig "},{"id":2,"name":" The kitten "}] 
* @param path  The web path  
* @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 HttpURLConnection object , We can get web page data from the network . 
conn.setConnectTimeout(5 * 1000); //  In milliseconds, set the timeout to 5 seconds  
conn.setRequestMethod("GET"); // HttpURLConnection Is through the HTTP Protocol request path Path, so you need to set the request mode , It can be left unset because it defaults to GET 
if (conn.getResponseCode() == 200) {//  Determine whether the request code is 200 Code, otherwise fail  
InputStream is = conn.getInputStream(); //  Get the input stream  
byte[] data = readStream(is); //  Replace the input stream with an array of characters  
json = new String(data); //  Converts an array of characters into a string  

// Data form: [{"id":1,"name":" The pig ","age":22},{"id":2,"name":" The kitten ","age":23}] 
JSONArray jsonArray = new JSONArray(json); // The data is directly 1 It's an array, so it's straightforward   with android Provided framework JSONArray read JSON Data, convert to Array 

for (int i = 0; i < jsonArray.length(); i++) { 
JSONObject item = jsonArray.getJSONObject(i); // Each record consists of several Object An object  
int id = item.getInt("id"); //  Gets the value of the object  
String name = item.getString("name"); 

map = new HashMap<String, String>(); //  Deposit to MAP inside  
map.put("id", id + ""); 
map.put("name", name); 
list.add(map); 
} 
} 

// *********** The 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; 
} 

/** 
*  To obtain " Objects form " the JSON The data,  
*  Data form: {"total":2,"success":true,"arrayData":[{"id":1,"name":" The pig "},{"id":2,"name":" The kitten "}]} 
* @param path  The web path  
* @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 HttpURLConnection object , We can get web page data from the network . 
conn.setConnectTimeout(5 * 1000); //  In milliseconds, set the timeout to 5 seconds  
conn.setRequestMethod("GET"); // HttpURLConnection Is through the HTTP Protocol request path Path, so you need to set the request mode , It can be left unset because it defaults to GET 
if (conn.getResponseCode() == 200) {//  Determine whether the request code is 200 Code, otherwise fail  
InputStream is = conn.getInputStream(); //  Get the input stream  
byte[] data = readStream(is); //  Replace the input stream with an array of characters  
String json = new String(data); //  Converts an array of characters into a string  


// Data form: {"total":2,"success":true,"arrayData":[{"id":1,"name":" The pig "},{"id":2,"name":" The kitten "}]} 
JSONObject jsonObject=new JSONObject(json); // The form of the data returned is 1 a Object Type, so it can be converted directly to 1 a Object 
int total=jsonObject.getInt("total"); 
Boolean success=jsonObject.getBoolean("success"); 
Log.i("abc", "total:" + total + " | success:" + success); // The test data  

JSONArray jsonArray = jsonObject.getJSONArray("arrayData");// There is a 1 Two arrays of data that you can use getJSONArray Access to an array  
for (int i = 0; i < jsonArray.length(); i++) { 
JSONObject item = jsonArray.getJSONObject(i); //  Get each object  
int id = item.getInt("id"); //  Gets the value of the object  
String name = item.getString("name"); 

map = new HashMap<String, String>(); //  Deposit to MAP inside  
map.put("id", id + ""); 
map.put("name", name); 
list.add(map); 
} 
} 

// *********** The 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; 
} 


/** 
*  Gets a complex type JSON data  
* Data form:  
{"name":" The pig ", 
"age":23, 
"content":{"questionsTotal":2, 
"questions": [ { "question": "what's your name?", "answer": " The pig "},{"question": "what's your age", "answer": "23"}] 
} 
} 
* @param path  The web path  
* @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 HttpURLConnection object , We can get web page data from the network . 
conn.setConnectTimeout(5 * 1000); //  In milliseconds, set the timeout to 5 seconds  
conn.setRequestMethod("GET"); // HttpURLConnection Is through the HTTP Protocol request path Path, so you need to set the request mode , It can be left unset because it defaults to GET 
if (conn.getResponseCode() == 200) {//  Determine whether the request code is 200 Code, otherwise fail  
InputStream is = conn.getInputStream(); //  Get the input stream  
byte[] data = readStream(is); //  Replace the input stream with an array of characters  
String json = new String(data); //  Converts an array of characters into a string  


/* Data form:  
{"name":" The pig ", 
"age":23, 
"content":{"questionsTotal":2, 
"questions": [ { "question": "what's your name?", "answer": " The pig "},{"question": "what's your age", "answer": "23"}] 
} 
} 
*/ 
JSONObject jsonObject=new JSONObject(json); // The form of the data returned is 1 a Object Type, so it can be converted directly to 1 a Object 
String name=jsonObject.getString("name"); 
int age=jsonObject.getInt("age"); 
Log.i("abc", "name:" + name + " | age:" + age); // The test data  

JSONObject contentObject=jsonObject.getJSONObject("content"); // Gets an object within an object  
String questionsTotal=contentObject.getString("questionsTotal"); // Get inside the object 1 A value  
Log.i("abc", "questionsTotal:" + questionsTotal); // The test data  

JSONArray contentArray=contentObject.getJSONArray("questions"); // Gets 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 value of the object  
String answer = item.getString("answer"); 

map = new HashMap<String, String>(); //  Deposit to MAP inside  
map.put("question", question); 
map.put("answer", answer); 
list.add(map); 
} 
} 

// *********** The 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; 
} 




/** 
*  Replace the input stream with an array of characters  
* @param inputStream  The input stream  
* @return  A 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 articles: