JSON Quick Start

Source: Internet
Author: User

1. What is json?JavaScript Object Notation is a lightweight data exchange format. Easy to read and write. It is also easy to parse and generate machines. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language.
Ii. Comparison between xml and json:
Xml:Advantages: (1 ). xml is a common data format (2 ). instead of adding data to a defined format, you need to customize a proper tag for the data (3 ). dom can be used to fully control the disadvantages of the document: (1 ). if the document is from the server, you must ensure that the document contains the correct header information. If the document type is incorrect, the value of responseXML is null. (2). dom parsing may be complicated when the browser receives a long xml file. (3) Both the server side and the client side need to spend a lot of code to parse the XML, which makes the server side and client code abnormal and complex and difficult to maintain;Json:Advantages:

(1) the data format is relatively simple, easy to read and write, the format is compressed, and the bandwidth usage is small;

(2) Easy to parse. The client JavaScript can simply read JSON data through eval_r;

(3) supports multiple languages, including ActionScript, C, C #, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby, and other server-side languages, facilitating server-side parsing;

(4) In the PHP world, there has been a PHP-JSON and JSON-PHP appear, partial to the PHP serialized program directly called, PHP server objects, arrays, etc. can directly generate JSON format, facilitate client access extraction;

(5) because the JSON format can be used directly for server-side code, it greatly simplifies the development of server-side and client-side code, and completes tasks unchanged and is easy to maintain.

Disadvantages:

(1) It is widely used and widely used without the XML format. It is not as universal as XML;

(2) The JSON format is still in the initial stage in Web Service promotion.

Comparison:

(1) In terms of readability, the data readability of JSON and XML is basically the same. The readability of JSON and XML is comparable. One side is the suggested syntax and the other side is the standard tag format, which makes it difficult to distinguish between the two.

(2) In terms of scalability, XML is inherently well scalable, and JSON is also available. There is nothing XML can be extended, and JSON cannot.

(3) In terms of encoding difficulty, XML has a variety of encoding tools, such as Dom4j and JDom. JSON also provides tools provided by json.org, but JSON encoding is much easier than XML, JSON code can be written without tools, but it is not easy to write XML.

(4) In terms of decoding difficulty, the parsing of XML should take into account the parent node of the child node, which is confusing, while the difficulty of JSON Parsing is almost 0. There is nothing to say about XML.

(5) XML has been widely used in the industry in terms of popularity, and JSON is just the beginning. However, in the specific field of Ajax, the future development of XML must be in JSON. Then Ajax should be changed to Ajaj (Asynchronous Javascript and JSON.

(6)JSON and XML have rich parsing methods.

(7) JSON is smaller than XML.

(8) JSON and JavaScript interaction is more convenient.

(9) JSON is less descriptive than XML.

(10) JSON is much faster than XML.

Note: lightweight and heavyweight comparison of data exchange formats:

Lightweight and heavyweight are relative, so what is the significance of XML compared with JSON? I think it should be reflected in parsing. XML currently has two parsing Methods: DOM and SAX;

The DOM regards XML as a DOM object in a data exchange format and needs to read the XML file into the memory. In this regard, the principles of JSON and XML are the same, however, XML should take into account the Parent and Child Nodes. JSON Parsing is much less difficult, because JSON is constructed in two structures: key/value, a set of key-value pairs; an ordered set of values, which can be understood as an array;

SAX does not need to read the entire document to process the parsed content. It is a step-by-step parsing method. The program can terminate the resolution at any time. In this way, a large document can be gradually presented at 1.1 points, so SAX is suitable for large-scale parsing. JSON cannot be used at present.

Therefore, the lightweight/heavyweight difference between JSON and XML is that JSON only provides the overall resolution scheme, and this method can only achieve good results when parsing less data; XML provides a step-by-step resolution solution for large-scale data, which is suitable for processing large amounts of data.

3. A simple json example:
Var rich = {"name": "sjj", "age": "23", "address": [{"province": "anhui", "city ": "anqing" },{ "province": "beijing", "city": "haidian"}], "wife": {"name": "gl ", "age": "20", "husband": "sjj" }}; // js identifies the json Data Format: alert (rich. name); alert (rich. address [0]. province); alert (rich. address [0]. city); alert (rich. address [1]. province); alert (rich. address [1]. city); alert (rich. wife. name); alert (rich. wife. age); alert (rich. wife. husband );
Iv. json writing formatJson syntax is simple and easy to understand. The details are as follows: Syntax Rules:
  • Data in name/value pairs
  • Data is separated by commas (,).
  • Brackets save objects
  • Square brackets Save the JSON value of the array:
    • Number (integer or floating point number)
    • String (in double quotation marks)
    • Logical value (true or false)
    • Array (in square brackets)
    • Object (in curly brackets)
    • Null
      JSON name/value pair

      Name/value pair includes the field name (in double quotation marks), followed by a colon, followed by a value:

      "FirstName": "John"
      JSON object:

      JSON objects are written in curly brackets: objects can contain multiple name/value pairs:

      {"FirstName": "John", "lastName": "Doe "}
      JSON Array

      JSON array is written in square brackets:

      An array can contain multiple objects:

      {"employees": [{ "firstName":"John" , "lastName":"Doe" },{ "firstName":"Anna" , "lastName":"Smith" },{ "firstName":"Peter" , "lastName":"Jones" }]}
      For more information, see http://json.org /. Let's take a look at the following figures (similar to the Conversion Diagram corresponding to the automatic machine in the Compilation Principle ):




      V. eval method and json format in java script In general, our json data is obtained from the server, and the obtained json data is returned in the form of a string. Although this string is in json format, it cannot be used directly. We must convert this string into an object to parse it normally,Eval () function <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3ryb25update/crop + crop = "brush: java;"> var data = "{'name': 'rowandjj '}"; // This is a string! Data = eval ("(" + data + ")"); alert (data. name); // output rowandjj We noticed that we added a parentheses in the eval function. Why? The purpose of parentheses is to force the eval function to evaluate JavaScript code. Forcibly convert expressions in parentheses into objectsInstead of being executed as a statement. For example, if the object {} is not added with outer brackets, eval identifies the braces as the start and end mark of the JavaScript code block, then {} is considered to have executed an empty statement. 6. parse json data There are dozens of json data parsing methods, commonly used google Gson, json-org, and json-lib. Here take json-lib as an example: Step: 1. Import the json-lib.jar package and its dependent package: commons-beanutils, commons-collections, commons-lang, commons-logging, ezmorph. 2. Write the Code:
      Package cn.edu. chd. test; import java. util. arrayList; import java. util. list; import net. sf. json. JSONArray; import net. sf. json. JSONObject; import net. sf. json. jsonConfig; import cn.edu. chd. domain. person;/*** @ author Rowand jj ** use json-lib to parse and construct json data */public class JSONDemo {public static void main (String [] args) {// func1 (); // func2 (); func3 ();}/*** convert javabean to json format */public static void func1 () {Person p = new Person ("rowandjj", 23); JSONObject jsonObj = JSONObject. fromObject (p); // construct a jsonobject. The parameter is a javabean object System. out. println (jsonObj. toString (); // converts a java object to json data ---> {"age": 23, "name": "rowandjj"} System. out. println (jsonObj. getString ("name"); // you can obtain the attribute value ----> rowandjj }/***
             
              
      Set to json data */public static void func2 () {List
              
               
      List = new ArrayList
               
                
      (); List. add (new Person ("zhangsan", 11); list. add (new Person ("lisi", 12); list. add (new Person ("wangwu", 13); JSONArray jsonArr = JSONArray. fromObject (list); // convert the set data to json data // [{"age": 11, "name": "zhangsan" },{ "age": 12, "name": "lisi" },{ "age": 13, "name": "wangwu"}] System. out. println (jsonArr. toString (); // The returned result is as follows: System. out. println (jsonArr. getJSONObject (0 ). getString ("name"); // return the name attribute value of the first element in the json array, that is, zhangsan}/*** filters out some attribute values in the javabean object, convert the remaining property-value to json format */public static void func3 () {Person p = new Person ("rowandjj", 23); JsonConfig config = new JsonConfig (); config. setExcludes (new String [] {"age"}); // filter out the age attribute JSONObject jsonObj = JSONObject. fromObject (p, config); // pass the filter to System. out. println (jsonObj. toString (); // {"name": "rowandjj "}}}
               
              
             
      VII. Case studies 1. Simulate the server (here a servlet is used to process the request) to send json data to the client, and the client obtains and displays the data. Requested servlet:
      Package cn.edu. chd. web; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class JSONServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp. setContentType ("text/html; charset = UTF-8"); resp. setCharacterEncoding ("UTF-8"); PrintWriter writer = resp. getWriter (); String jsondata = "{'name': 'rowandjj ', 'job': 'student'}"; // return the json data writer to the client. println (jsondata );}
      Page (Part ):
          My name is
      My career is
      Js script:
      <Script type = "text/javascript"> window. onload = function () {var xhr = createXmlHttpRequest (); xhr. open ("get", "/AJAX/servlet/JSONServlet? Time = "+ new Date (). getTime (); xhr. send (null); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200 | xhr. status = 304) {var data = xhr. responseText; // get the returned json data. Note that the data here is string type data = eval ("(" + data + ")"); // convert the json string to the json object var name = data. name; var job = data. job; document. getElementById ("name "). innerText = name; document. getElementById ("job "). innerText = job ;}}} function createXmlHttpRequest () {// create the XMLHttpRequest object var xmlHttp; try {// Firefox, Opera 8.0 +, Safari xmlHttp = new XMLHttpRequest ();} catch (e) {try {// Internet Explorer xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");} catch (e) {try {xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ") ;}catch (e) {}} return xmlHttp ;}</script>
      Display Effect:


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.