JSON, JSON for data exchange, json for data exchange
1. JSON
1.1. JSON
1.1.1.What is JSON
JSON is the Javascript Object Notation, which is a mainstream data exchange format. The reason for its wide application is determined by its ease of reading.
Simple: only six types of symbols [] {}; can represent any type of complex objects or arrays.
Easy to read, machine parsing, or human reading can quickly find the required information from this format.
1.1.2.Platform-independent data exchange
JSON, as a data exchange format, is irrelevant to the platform type. Whether the server uses Java, C #, or other languages, the string format can be converted to an object of a specific language. Similarly, any language can convert its own object to a JSON string.
1.1.3.Lightweight Solutions
The lightweight JSON is faster than the XML data exchange format, and the documentation is smaller. XML files contain hierarchical relationships of many objects, which is inconvenient for parsing and conversion. If there are more characters, the file is too large. All these drawbacks of JSON have been overcome, and simple symbols are faster to parse.
1.2. JSONSyntax
1.2.1. JSONStructure
There are two main structures for data exchange using JSON. One is to use the "name-value" pair to represent an object, and the other is the ordered list of values, that is, the array. Based on these two structures, nesting can be performed between them. That is, the object value can be an array or an object, and a value in the array can be an object or an array.
Objects, records, structures, dictionaries, and hash tables in different languages can all be used as the basic structure of converted objects.
1.2.2.Use JSON to represent an object
When JSON is used to represent an object, the basic syntax structure starts with braces and ends with braces. Each attribute in braces is separated by a comma. Each attribute group is implemented by a pair of attribute names and attribute values. For example, an employee object can be written in the following structure:
{'Id': 1, 'name': 'wang Xiaoji ', 'age': 24}
No matter how complicated the structure is, as long as you see the braces, it represents this object. As for the internal attributes, you only need to ensure that they are separated by commas.
Each set of attributes should follow the following principles when writing:
- Attribute names must be enclosed by quotation marks.
- Attribute value types can be diverse, including string, number, true, false, null, object, array
- If the type of the attribute value is a string, it must be enclosed by quotation marks.
As long as the object structure conforms to the syntax structure, you can access a property value in the format of "object. property name" when accessing an attribute. For the above employee object, you can use the following code to obtain the value of the name attribute "Wang Xiaoyu:
Var obj = {'id': 1, 'name': 'wang Xiaoji ', 'age': 24 };
Var name = obj. name;
If a property value of an object is still an object, the definition structure is as follows:
Var obj = {'id': 1, 'name': 'wang Xiaoji ', 'dep': {'depid': 1, 'depname': 'finance '}};
Var depName = obj. dep. depName;
The object property can be an object. when accessing this object property, it still follows the "object. in the above object, obj is an object that also contains the structure of the object, and dep is the property name, {'depid': 1, 'depname ': 'Finance authorization'} is the attribute value, that is, the Department attribute includes the Department ID and department name attributes. Therefore, you must use the multilevel point format for the attribute in the access property.
1.2.3.Use JSON to represent an array
When JSON is used to represent an array, it must start with square brackets and end with square brackets. As long as you see square brackets, you must think of it as an array. Multiple values in the array are separated by commas. Syntax:
[Value, value, value... ]
The value type can be string, number, false, true, null, object, or array. To represent an array of three employees, you can use the following format:
Var jsonArr = [{'id': 1, 'name': 'wang Xiaoji '}, {'id': 2, 'name': 'huang xiaoxian '}, {'id': 3, 'name': 'old Wang '}];
If you want to access the name of the second element in the array, the Code is as follows:
Var name = jsonArr [1]. name;
The elements in the array can still be nested with arrays, and the object attributes can also be nested with arrays, with the following code:
Var jsonObj = {'id': 1, 'name': 'wang Xiaoji ', 'salary': [{'month': 1, 'number': 5000 }, {'month': 2, 'number': 4000}]};
For nested data types, the principle is that the object is accessed through ".", and the array is accessed through the "[]" subscript. For the above objects, if you want to know the employee's salary in March, the access form is as follows:
Var number = jsonObj. salary [1]. number;
2.Data exchange using JSON
2.1.Data Exchange
2.1.1.Data exchange principle
JSON, as the data exchange format, must have a corresponding conversion process on the client and server. If the client requests data, the server converts the Java object to a JSON string first. After the response transmits the string to the client, the client receives the conversion result, however, JavaScript requires that the string be converted into an object format for easier access. Therefore, in the JavaScript code of the client, the JSON string must be converted into an object that can be recognized by JavaScript, this completes the entire transformation process from the server-side object to the client object.
Similarly, if you want to submit data to the server after the client fills in the data, you must first construct the client data into a JSON object string and transmit it to the server through the network, the server then converts the JSON string into an object recognized by Java based on the conversion rules.
2.1.2. JavaConvert an object to JSON
You can use official APIs to convert server-side objects. JSONObject and JSONArray are conversion types of objects and arrays respectively.
The following code is used to convert objects using these two types:
The conversion code for arrays is as follows:
List <Employee> emps = new ArrayList <Employee> ();
For (int I = 0; I <3; I ++ ){
Employee s = new Employee ();
S. setId (I + 1 );
S. setName ("Bear" + I );
S. setGender ("male ");
Emps. add (s );
}
JSONArray jsonArr = JSONArray. fromObject (emps );
String jsonStr = jsonArr. toString ();
2.1.3. JSONConvert string to JS object
When JSON is transmitted to the client, the conversion from JSON to JavaScript objects needs to be completed. If JavaScript native method is used for conversion, you can use the eval () method, however, the left and right parentheses must be connected before and after the JSON, such:
Var jsonObj = eval ("(" + json ")");
Why do you want to add ('+ json +') to eval?
The reason is the eval issue. Json starts and ends in the form of "{}". In JS, json is treated as a statement block. Therefore, it must be forcibly converted into an expression. The purpose of parentheses is to force the eval function to forcibly convert the expressions in parentheses into objects when processing JavaScript code, rather than being executed as statements.
However, it should be noted that the eval () method dynamically executes the strings (which may be JavaScript scripts), which can easily cause system security problems. Therefore, you can use third-party client script libraries that circumvent eval (), such as the evalJSON () method provided in prototype. js. You can use this extension library after introducing the prototype. js file in the page. The implementation code is as follows:
<Script type = "text/javascript" src = "js/prototype-1.6.0.3.js"> </script>
<Script type = "text/javascript">
Function f1 (){
Var xhr = getXhr ();
Xhr. open ('get', 'quoto. do ', true );
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4 ){
Var txt = xhr. responseText;
// Convert a json string to a javascript Object or Array
Var arr = txt. evalJSON ();
}
};
Xhr. send (null );
}
</Script>
2.2.Cache Problems
2.2.1.What is cache?
When sending a GET request, the AJAX object provided by IE browser first checks whether the address has been accessed. If the address has already been accessed, the browser will not send the request again.
After all, the page displays data when you click a function for the first time. However, if you repeatedly click to obtain the latest data, the page does not change, the request is rejected because the browser finds that the address is the same.
However, this page only appears in IE. Both Chrom and Firefox can achieve data acquisition and page refresh.
2.2.2.How to solve cache Problems
To solve the cache problem, you need to cheat the browser and make it think that the address of each request is different. To build different URLs, add the previous random number. The code format is as follows:
Xhr. open ('get', 'getnumber. do? '+ Math. random (), true );
Math. random () can generate random numbers between 0 and 1, so that different addresses can be generated each time, and the browser can resend the request to refresh the data.
The second method to solve the cache problem is not to use the GET request method. If it is changed to POST for submission, the browser will not judge the address.
2.3.Synchronization problems
2.3.1.What is synchronization?
A synchronous request means that after an AJAX object sends a request, the browser must wait for the response to return and then allow the page to continue operations, in the form of a false dead state of the page. It is like you can do the next thing only after you finish one thing. Asynchronous mode does not require such a wait. There is a feeling that two things can be done at the same time.
2.3.2.How to send synchronous requests
Sending a synchronous request is the third parameter of the open method. If it is set to false, it indicates a synchronous request. If it is set to true, it indicates an asynchronous request.
The Code is as follows:
Xhr. open ('get', 'check... ', false );
2.3.3.Use Cases of synchronous requests
Synchronous requests are generally applied when form verification is required to wait for the verification to return before clicking submit. Synchronous requests can also be used to notify the Server Client to close the onunload Event. Some applications need to know whether the client closes the window, this determines whether to release the resources allocated by the server to the client. If the client closes the browser, the server can be notified in the onunload Event. However, if the server is disabled before the server returns, it will not know whether the release is successful, therefore, the synchronization method is usually used to wait for the server's response, which can ensure the release of server resources to a certain extent.