Home > Web Front-end > JS Tutorial > body text

JSON Getting Started Guide Friends who want to understand json can read_json

WBOY
Release: 2016-05-16 18:47:46
Original
982 people have browsed it

Although there is a lot of publicity about how XML has cross-platform and cross-language advantages, however, unless it is applied to Web Services, in ordinary Web applications, developers often struggle with the parsing of XML, whether it is generated on the server side. Either processing XML, or the client using JavaScript to parse XML, often leads to complex code and extremely low development efficiency. In fact, for most web applications, they do not need complex XML to transmit data at all, XML's extensibility rarely has an advantage, and many AJAX applications even directly return HTML fragments to build dynamic web pages. Compared to returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but it also lacks a certain degree of flexibility.
JSON now provides web application developers with an alternative data exchange format. Let’s take a look at what exactly JSON is. It offers greater simplicity and flexibility than XML or HTML fragments.
Ajax Resource Center
Visit the Ajax Resource Center, your one-stop center for information about the Ajax programming model, including documentation, tutorials, forums, blogs, wikis, and news. Any new information on Ajax can be found here.
JSON data format analysis
Like XML, JSON is also a data format based on plain text. Since JSON is inherently prepared for JavaScript, the data format of JSON is very simple. You can use JSON to transmit a simple String, Number, Boolean, an array, or a complex Object.
String, Number and Boolean are very simple to represent in JSON. For example, using JSON to represent a simple String "abc", its format is:
"abc"
In addition to the characters ",, / and some control characters (, f, , , ) need to be encoded, other Unicode characters can be output directly. The following figure is the complete representation structure of a String:
Figure 1. The complete representation structure of String
A Number can be represented as follows according to an integer or floating point number:
Figure 2. The representation structure of Number
This It is consistent with the representation method of most programming languages, for example:
12345 (integer)
-3.9e10 (floating point number)
Boolean type is represented as true or false. Additionally, null in JavaScript is represented as null. Note that true, false, and null do not have double quotes, otherwise they will be treated as a String.
JSON can also represent an array object, using [] to contain all elements, each element separated by commas, and the elements can be any Value. For example, the following array contains a String, Number, Boolean and a null:
["abc",12345,false,null]
Object objects are represented in JSON by {} containing a series of unordered Key-Value pairs. In fact, the Object here is equivalent to the one in Java. Map, rather than Java's Class. Note that Key can only be represented by String.
For example, an Address object contains the following Key-Value:
city:Beijing
street:Chaoyang Road
postcode:100025 (integer)
Represented in JSON as follows:
{"city ":"Beijing","street":" Chaoyang Road ","postcode":100025}
Value can also be another Object or an array. Therefore, complex Objects can be nested to represent, for example, a Person object Contains name and address objects, which can be expressed as follows:
{"name":"Michael","address":
{"city":"Beijing","street":" Chaoyang Road ","postcode" :100025}
}
JavaScript processing JSON data
The above introduces how to use JSON to represent data. Next, we also need to solve how to generate JSON format data on the server side for sending. to the client, and how the client uses JavaScript to process JSON-formatted data.
Let’s first discuss how to use JavaScript to process JSON data in web pages. We can see how the client represents JSON data to the user through a simple JavaScript method:
function handleJson() {
var j={"name":"Michael","address":
{"city":"Beijing","street":" Chaoyang Road ","postcode":100025}
};
document.write(j.name);
document.write(j .address.city);
}
Assume that the JSON data returned by the server is as above:
{"name":"Michael","address":
{"city":"Beijing ","street":" Chaoyang Road ","postcode":100025}
}
Just assign it to a JavaScript variable, you can use the variable immediately and update the information on the page. Compared with XML Needs to read various nodes from the DOM, using JSON is very easy. All we need to do is send an Ajax request and assign the JSON data returned by the server to a variable. There are many Ajax frameworks that already include the ability to process JSON data. For example, Prototype (a popular JavaScript library: http://prototypejs.org) provides the evalJSON() method, which can directly turn the JSON text returned by the server into a JavaScript variable. :
new Ajax.Request("http://url", {
method: "get",
onSuccess: function(transport) {
var json = transport.responseText.evalJSON() ;
// TODO: document.write(json.xxx);
}
});
Output JSON format data on the server side
Let’s discuss how to The server outputs data in JSON format.Taking Java as an example, we will demonstrate encoding a Java object into JSON-formatted text.
When encoding a String object into JSON format, you only need to handle special characters. In addition, strings must be represented by (") instead of ('):

Copy code The code is as follows:

static String string2Json(String s) {
StringBuilder sb = new StringBuilder(s.length() 20);
sb.append('"');
for (int i=0 ; ichar c = s.charAt(i);
switch (c) {
case '"':
sb.append("\ "");
break;
case '\':
sb.append("\\");
break;
case '/':
sb.append( "\/");
break;
case 'b':
sb.append("\b");
break;
case 'f':
sb. append("\f");
break;
case 'n':
sb.append("\n");
break;
case 'r':
sb.append("\r");
break;
case 't':
sb.append("\t");
break;
default:
sb .append(c);
}
}
sb.append('"');
return sb.toString();
}

will It is much easier to express Number as JSON. Using Java's polymorphism, we can handle various Number formats such as Integer, Long, and Float:
Copy code The code is as follows:

static String number2Json(Number number) {
return number.toString();
}

Boolean type You can also get the JSON representation directly through the toString() method:
Copy code The code is as follows:

static String boolean2Json(Boolean bool) {
return bool.toString();
}

To encode the array into JSON format, you can encode each element through a loop:
Copy code The code is as follows:

static String array2Json(Object[] array) {
if (array.length==0)
return "[]";
StringBuilder sb = new StringBuilder(array.length << 4);
sb.append('[');
for (Object o : array) {
sb.append(toJson(o));
sb.append(',');
}
// Add the last ' ,' becomes ']':
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}

Finally, we need to encode Map into JSON format, because JavaScript's Object actually corresponds to Java's Map. The method is as follows:
Copy code The code is as follows:

static String map2Json(Map map) {
if (map.isEmpty())
return "{}";
StringBuilder sb = new StringBuilder(map.size() << 4);
sb .append('{');
Set keys = map.keySet();
for (String key : keys) {
Object value = map.get(key);
sb.append('"');
sb.append(key);
sb.append('"');
sb.append(':');
sb.append( toJson(value));
sb.append(',');
}
// Change the last ',' to '}':
sb.setCharAt(sb.length( )-1, '}');
return sb.toString();
}

In order to uniformly handle any Java object, we write an entry method toJson(Object), Able to encode any Java object into JSON format:
Copy code The code is as follows:

public static String toJson(Object o) {
if (o==null)
return "null";
if (o instanceof String)
return string2Json((String)o);
if (o instanceof Boolean)
return boolean2Json((Boolean)o);
if (o instanceof Number)
return number2Json((Number)o);
if (o instanceof Map)
return map2Json((Map)o);
if (o instanceof Object[])
return array2Json((Object[])o);
throw new RuntimeException("Unsupported type : " o.getClass().getName());
}

We do not perform strict checks on Java objects. Unsupported objects (such as List) will directly throw RuntimeException. In addition, in order to ensure that the output JSON is valid, the Key of the Map object cannot contain special characters. Careful readers may also find that circularly referenced objects can cause infinite recursion. For example, by carefully constructing a circularly referenced Map, a StackOverflowException can be detected:
Copy code The code is as follows:

@Test(expected=StackOverflowError.class)
public void testRecurrsiveMap2Json() {
Map map = new HashMap();
map.put("key", map);
JsonUtil.map2Json(map);
}

Fortunately, the server handles it The JSON data should eventually be converted into simple JavaScript objects, so the possibility of recursive references is slim.
Finally, when outputting JSON through a Servlet or MVC framework, you need to set the correct MIME type (application/json) and character encoding. Assuming that the server uses UTF-8 encoding, you can use the following code to output the encoded JSON text:
Copy code The code is as follows:

response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter pw = response.getWriter() ;
pw.write(JsonUtil.toJson(obj));
pw.flush();

Summary
JSON is already part of the JavaScript standard. Currently, mainstream browsers have very complete support for JSON. By using JSON, we can get rid of XML parsing. For those Web 2.0 websites that use Ajax, JSON is indeed the most flexible and lightweight solution at present.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template