About JSON
JSON as a lighter, more friendly Web services client format (used in the form of a browser or visit the REST style of Web services, Ajax application form) in the Web service provider's attention.
This article described the design of Web services in the JSON in the causes of the most respected, as well as the XML as an alternative to the main advantages and limitations. The paper will explore in depth: With the Web Services Client choose to use JSON, how easy Java Web services in the JSON output generated.
Crossroads XML: Ajax XML browsers and design principles have been released for nearly a decade. Today, this markup language has been in the broad field of software applications has dominated. From Java,. NET platform in the mainstream, such as the configuration and deployment descriptor to the application integration scenario more complex applications, XML born of the language has nothing to do to occupy the minds of software architect in a unique position. But even if the authority of the most famous of XML has to admit: In some environments, XML's use has exceeded the capacity of its own limits.
Ajax built around principles of Web applications that illustrate the viability of XML, from this point of view, a new payload format also benefited from the development and expansion of XML. This new payload format is JavaScript Object Notation (JSON). In exploring this new markup language complexity, first to analyze the design in this unique form, XML with what limitations.
Ajax used to set up a remote Web services send and receive data channel of an independent, thus allowing the implementation of Web procedures outside the channel (out-of-band) client / server calls.通俗地说, Ajax update process and navigation sequence in a typical client / server environment to complete, in the background (that is, outside the channel) received information, the need for a full screen refresh.
These applications are usually updated through the REST-style (RESTful) Web services received, once the user's browser to receive, on the need to integrate into the overall layout of HTML pages, and XML This is an occasion to play a powerful force. Despite the recent years, the scripting language support and plug-ins support the majority of the mainstream functions of the browser has been enhanced, but many tasks are still difficult to carry out programming, one of which is the manipulation or handling of text, this is usually achieved using the DOM.
The complexity of the use of DOM derived from the root based on the function, which makes the data tree are simple to modify or access the need for numerous method calls. In addition, as we all know, DOM browser in a variety of implementation details vary, the process will lead to highly complex programming model, and its cross-browser compatibility problems with the possibility of greatly. The next obvious question is: how to make a markup language easily integrated into HTML pages in order to meet the requirements of Ajax?
The answer is: the use of all the mainstream browsers a common component - JavaScript engine. Need to use XML like DOM mechanism to access data and data integration into the layout, the use of this method, we no longer use such a format like XML to deliver Ajax update, instead of using a more simple and intuitive way using JavaScript engine to match the format of the natural - that is, JSON.
Have been identified since the XML and JSON and the relationship between Ajax, the following will be to further explore the technical details behind the JSON.
JSON analysis: the strengths and weaknesses of the JSON, first and foremost, understand, like XML and JSON is a simple text format. Compared to XML, it is more readable, more user-friendly visual inspection. Level in the syntax, JSON and other formats is the difference between the character data is separated, JSON limited separator in single quotation marks, parentheses, in brackets, braces, a colon and a comma. The chart is a JSON payload:
( "addressbook": ( "name": "Mary Lebow", "address": ( "street": "5 Main Street" "city": "San Diego, CA", "zip": 91912,), "phoneNumbers ": [" 619 332-3452 "," 664 223-4667 "]))
Will be above JSON payload using XML rewritten as follows:
<addressbook> <name> Mary Lebow </ name> <address> <street> 5 Main Street </ street> <city zip="91912"> San Diego, CA </ city> <phoneNumbers> <phone> 619 332 -- 3452 </ phone> <phone> 664 223-4667 </ phone> </ phoneNumbers> </ address> </ addressbook>
Is it very similar? But they are not the same. The following will elaborate on the advantages of using JSON syntax and inadequate.
At first glance the advantages of the use of JSON data separator may not be the advantage of less obvious, but there is a fundamental reason: they simplify data access. Separator to use when these data, JavaScript engine on the data structure (such as strings, arrays, objects) that coincided with the internal the same as these symbols.
This will create a DOM technology more than a convenient means of data access. Here are a few JavaScript code fragments to illustrate the process, they will visit the previous snippet of code fragments in the JSON message:
JSON in the name of the visit: addressbook.name visit JSON address: addressbook.address.street access phone numbers in JSON first: addressbook.address.phoneNumbers [0] If you have the DOM programming experience, you can quickly see the difference;
Another advantage of JSON is that it's non-long sex. In XML, the opening and closing tag is necessary in order to meet compliance mark; in JSON, all these requirements only by a simple brackets to meet. Contains hundreds of fields in the data exchange, the traditional marker of the XML data exchange time will be extended. There are no formal studies have shown that XML than JSON online higher transmission efficiency; it is only through a simple comparison of the number of bytes, the equivalent JSON and XML payload, which is always smaller than the latter. As the gap between them how much, especially in the new format of the XML compression how much the gap between them, pending further study.
In addition, JSON by a different programming language at the developer's favor. This is because in the Haskell or Lisp or in more mainstream in C # and PHP, developers can easily generate JSON (see references).
Inadequate and many good things are the same two sides, JSON and the non-long is no exception, for which JSON has lost a number of characteristics of XML. Different context namespace to allow the same information in the above mixed with each other, however, apparently has been unable to find a JSON namespace. JSON and XML Another difference is the difference property, due to the use of JSON colon assignment, which will lead to when the XML into JSON, in Identifier (XML CDATA) and the actual property value it is difficult to differentiate between who should be when writing this consideration.
In addition, JSON fragment creation and verification process rather than the complexity of XML. From this point of view, XML in the development of tools leading to JSON. Nevertheless, in order to eliminate this area of your confusion may exist, the next section will introduce some of the most mature development of JSON.
JSON from Web services to generate JSON output since the primary objective of the browser from the outside channel of the request, so we have chosen to REST-style (RESTful) Web Services to generate such data. In addition to typical business logic into Web services, the API will also be a specific local Java structures into JSON format (see references). First of all, the following Java code to manipulate the Address Object:
/ / Create addressbook data structureSortedMap addressBook = new TreeMap ();// Create new address entries and place in Map / / (See download for Address POJO structure) Address maryLebow = new Address ( "5 Main Street", "San Diego, CA ", 91912," 619-332-3452 "," 664-223-4667 "); addressBook.put (" Mary Lebow ", maryLebow); Address amySmith = new Address (" 25 H Street "," Los Angeles, CA ", 95212," 660-332-3452 "," 541-223-4667 "); addressBook.put (" Sally May ", amySmith); Address johnKim = new Address (" 2343 Sugarland Drive "," Houston, TX " , 55212, "554-332-3412", "461-223-4667"); addressBook.put ( "John Kim", johnKim); Address richardThorn = new Address ( "14 68th Street", "New York, NY" ,, 12452, "212-132-6182", "161-923-4001"); addressBook.put ( "Richard Thorn", richardThorn);
Where the structure of the generated Java is not important (which may be in the JSP, Servlet, EJB, or POJO generated), it is important that, in the REST style of Web services have the right to use the data. Show as follows:
/ / Define placeholder for JSON responseString result = new String ();// Get parameter (if any) passed into application String from = request.getParameter ( "from"); String to = request.getParameter ( "to"); try (/ / Check for parameters, if passed filter address book if (from! = null & & to! = null) (/ / Filter address book by initial addressBook = addressBook.subMap (from, to);) / / Prepare the convert addressBook Map to JSON array / / Array used to place numerous address entries JSONArray jsonAddressBook = new JSONArray (); / / Iterate over filtered addressBook entries for (Iterator iter = addressBook.entrySet (). iterator (); iter.hasNext ();) (/ / Get entry for current iteration Map.Entry entry = (Map.Entry) iter.next (); String key = (String) entry.getKey (); Address addressValue = (Address) entry.getValue (); / / Place entry with key value assigned to "name" JSONObject jsonResult = new JSONObject (); jsonResult.put ( "name", key); / / Get and create address structure corresponding to each key / / appending address entry in JSON format to result String streetText = addressValue.getStreet (); String cityText = addressValue.getCity (); int zipText = addressValue.getZip (); JSONObject jsonAddress = new JSONObject (); jsonAddress.append ( "street", streetText); jsonAddress.append ( "city", cityText); jsonAddress.append ( "zip", zipText); jsonResult.put ( "address", jsonAddress); / / Get and create telephone structure corresponding to each key / / appending telephone entries in JSON format to result String telText = addressValue.getTel (); String telTwoText = addressValue.getTelTwo (); JSONArray jsonTelephones = new JSONArray (); jsonTelephones.put (telText); jsonTelephones.put (telTwoText); jsonResult.put ( "phoneNumbers", jsonTelephones) ; / / Place JSON address entry in global jsonAddressBook jsonAddressBook.put (jsonResult);) / / end loop over address book / / Assign JSON address book to result String result = new JSONObject (). put ( "addressbook", jsonAddressBook). toString ();) catch (Exception e) (/ / Error occurred)
In order to facilitate that, we have placed this code will be JSP (restservice.jsp) in. If it is for some procedures, then this sort of code will appear in the servlet or helper class. REST-style Web services first of all, extract the request of the two pass through the URL of the input parameters to it, according to these values the existing filter to adapt to the request address book. Filtered address book, you can check the beginning of the cycle in the Java mapping of each entry.
You will note that the internal circulation, json.org API is widely used in local Java into JSON format string. Although only a small number of categories (that is, JSONArray and JSONObject), but the API provides a wide range of the conversion method, and even the structure of XML can be converted into JSON output. But back to our Web services, once the cycle traversal of all entries, then the variable "result" will contain ready to return to the requesting party's address book the same part of the JSON.
Since JSON output has been generated, the following look at the other side of the equation: the browser application to use the JSON payload.
JSON as the payload of the use of browser-based client, we design most of the work involved in HTML, JavaScript to add additional JavaScript framework completed. Such as the use of Prototype library to easily create cross-browser Ajax-style calls. The following list contains applications of our the first part, and the corresponding JavaScript function.
<html> <head> <title> JSON Address Book </ title> <script type="text/javascript" src="prototype-1.4.0.js"> </ script> <script type = "text / javascript" > / / Method invoked when user changes letter rangefunction searchAddressBook () (/ / Select values from HTML select lists var fromLetter = $ F ( 'fromLetter'); var toLetter = = $ F ( 'toLetter'); / / Prepare parameters to send into REST web service var pars = 'from =' + fromLetter + '& to =' + toLetter; / / Define REST web service URL var url = 'restservice.jsp'; / / Make web service Ajax request via prototype helper, / / upon response, call showResponse method new Ajax.Request (url, (method: 'get', parameters: pars, onComplete: showResponse });}</ script> </ head>
First of all, into a prototype library, the library for the promotion of the REST style of Web services, Ajax call. Followed by searchAddressBook () function, when the user modify their choice of HTML as shown in the list, it will trigger this function. The function is triggered, the user will be given a HTML select list of options is selected and used to filter into two variables in the address book, and then point to the definition of a REST-style URL restservice.jsp Additional services variables.
This method also includes the function prototype with new Ajax.Request (url, (method: 'get', parameters: pars, onComplete: showResponse)); the actual Ajax Web service call; shows the URL of a relevant request, the request parameters included in the pars in; final once the Ajax request to terminate, that is, the implementation of showResponse ().
Below showResponse () as an example to evaluate the JSON payload and put HTML in the main layout of the environment necessary for the code.
/ / Method invoked when page receives Ajax response from REST web service function showResponse (originalRequest) (/ / Get JSON values jsonRaw = originalRequest.responseText; / / Eval JSON response into variable jsonContent = eval ( "(" + jsonRaw + ")" ); / / Create place holder for final response finalResponse = "<b>" + jsonContent.addressbook.length + "matches found in range </ b> <br/>"; / / Loop over address book length. for (i = 0; i <jsonContent.addressbook.length; i + +) (finalResponse + = "<hr/>"; finalResponse + = "<i> Name: </ i>" + jsonContent.addressbook.name + "<br/> "; finalResponse + =" <i> Address: </ i> "+ jsonContent.addressbook.address.street +" - "+ jsonContent.addressbook.address.city +", "+ jsonContent.addressbook.address.zip + ". <br/>"; finalResponse + = "<i> Telephone numbers: </ i>" + jsonContent.addressbook.phoneNumbers [0] + "&" + jsonContent.addressbook.phoneNumbers [1] + "."; ) / / Place formatted finalResponse in div element document.getElementById ( "addressBookResults"). innerHTML = finalResponse;)
Input parameters of this method is the REST style of Web services in response to calls to return. Since the advance has been aware of the need to deal with JSON string, then can use the JavaScript eval () function, will be the JSON string Add memory, and allows data access, it is so easy to develop the use of JSON. Do not need to resolve, a simple eval () can be JavaScript structure, we can manipulate the structure, like any other JavaScript to manipulate it.
Once the JSON response to eval after processing, will create a JavaScript cycle to extract the entry for each address, and each match into a container called finalResponse variables. The container itself contains all the necessary variables of the format for display in the Page Layout final address book. Cycle of the end of the match through document.getElementById ( "addressBookResults"). InnerHTML place finish.
Finally, in order to maintain the integrity of the physical layout of the page from the code consists of:
<body> <h4> Request address book matches: </ h4> <table cellpadding="15"> <tr> <td valign="top"> From: <br/> <select size = "15" onchange = " searchAddressBook () "> <option> A </ option> ... <option> Z </ option> </ select> </ td> <td valign="top"> To: <br/> <select size = "15" onchange = "searchAddressBook ()"> <option> A </ option> ... <option> Z </ option> </ select> </ td> <td valign="top"> <h5> Results </ h5> <div> Please select range </ div> </ td> </ tr> </ table> </ body>
Code above the list of the most worth mentioning is the HTML select list, because the amendment to trigger the need to call Java procedures outside the Ajax request channel. Secondly, <div> element is placed after the formatted JSON response places.
JSON right for you as in software design, like the choice of programming language, JSON choice depends on your own needs. If Web services users will be in the traditional, full-featured programming environment (such as Java,. NET, PHP, Ruby, etc.) to create, it is entirely possible not to use JSON. A given programming language environment for the majority of the unrestricted ability to provide complete control over the configuration (not to mention on the custom database, Analyzer or visit helper class), then JSON and XML and other Web services between the payload the difference is negligible.
The contrary, if the Web services user is limited in the browser environment, then JSON is the object worthy of serious consideration. In the browser using Web services is not interested in nature, but the actual business needs. If you need a load of data at this time there will not be any delay / refresh the "nice Web 2.0 interface", will have embedded in your browser Ajax and Web services technology.
In this case, you not only restricted access through the network to deal with the environment, but also by random user restrictions, forcing developers experienced the most common tools used in the browser to deal with text, such as: above DOM, and visit compared to JSON tree, DOM is very difficult to use.
You can download sample code and code related to this article.
json_addressbook.zip - sample code and utilities installed before extracting the files to be downloaded to addressbook.html, prototype-1.4.0.js and restservice.jsp Add any program directory. Json.jar will be contained to the selected program to copy / WEB-INF/lib directory. Visit <yourhost> / <yourappdir> / addressbook.html, and in the HTML select list. Everything is ready, you can run the JSON!
Conclusion Despite the "Ajax" in the "x" on behalf of XML, Web services also adhere to the use of XML format to become mainstream, but this does not mean perfect in this way. In the text processing, XML in Ajax application process has revealed some shortcomings. In this case, JSON becoming the eye-catching alternative to XML.
JSON syntax of the advantages and disadvantages of paper, as well as from the REST style Web services to create JSON output, how to embed Web page layout issues such as the introduction, you should now be able to provide end-users of the JSON support Web services, providing access to the current take advantage of this very large number of the format of the future of Web services.
Tags: web procedures (RSS), design principles (RSS), web applications (RSS), ajax (RSS), markup language (RSS), software architect (RSS), application integration (RSS), server data (RSS), data exchange (RSS), client server (RSS), 9a (RSS), web service provider (RSS), deployment descriptor (RSS), xml browsers (RSS), java web services (RSS), language complexity (RSS), payload format (RSS), technology applications (RSS), viability (RSS), software applications (RSS)
Permalink: http://www.codeweblog.com/about-json/





















