XML and JSON in Java

Source: Internet
Author: User

1. Introduction:

XML: extensible markup language, a language similar to HTML. It has no predefined tags and uses document type definition (DTD) to organize data. The format is uniform, cross-platform and language have long been recognized in the industry. For details, refer to Google or Baidu. Compared with JSON, a lightweight data exchange format, XML can be called heavyweight.

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.

2. Comparison

1) XML is heavyweight in the data exchange format, and JSON is lightweight. This is reflected in parsing.

Currently, XML has three parsing Methods: Dom, sax, and pull;

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.

2) Data Exchange Format comparison:

In terms of encoding, although both XML and JSON have their own encoding tools, JSON encoding is simpler than XML. Even if you do not use the tools, you can write JSON code, however, it is a little difficult to write good XML code. JSON, like XML, is also text-based and uses unicode encoding, and is as readable as XML in data exchange format.

Subjectively, JSON is clearer and redundant. The JSON website provides a strict description of the JSON syntax, but the description is short. In general, XML is more suitable for marking documents, while JSON is more suitable for data exchange processing.

In terms of parsing, in the common web application field, developers often use their brains for XML parsing. Both the server side generates or processes XML and the client side parses XML, which often leads to complicated code, extremely low development efficiency.

Compared with XML or HTML fragments, the data exchange format JSON provides better simplicity and flexibility.

Currently, the JSON format is still in the initial stage in Web Services, and is not as universal as XML. In Web Serivice applications, XML remains unshakable for the moment.

 

3. JSON Application

(1). JSON is a lightweight data exchange format.
(2) JSON is based on two data structures: object and array. The object is a set of "name/value" pairs.

(3). Android contains four JSON-related classes and one exceptions:

A. jsonobject

This is the basic unit related to the json definition in the system. It contains a pair of key/value values.

B. jsonarray

It represents a group of ordered values. The format of tostring output is enclosed in square brackets. Values are separated by commas (,) ([value1, value2, value3]).

C. jsonstringer

This class can help you quickly and conveniently create jsontext. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON text in strict accordance with the JSON syntax rules (syntaxrules. Each jsonstringer object can only create one JSON text. For example:

String mystring = new jsonstringer (). Object (). Key ("name"). Value (""). endobject (). tostring ();
Mystring = {"name": ""}

D. jsontokener

This is the class in which the system parses the JSON source string for the jsonobject and jsonarray constructors. It can extract numerical information from the source string.

E. jsonexception

(4) Example of JSON format

A. object instance:

{     "Image": {      "Width":  800,      "Height": 600,      "Title":  "View from 15th Floor",      "Thumbnail": {          "Url":    "http://www.example.com/image/481989943",          "Height": 125,          "Width":  "100"      },      "IDs": [116, 943, 234, 38793]    }}

B. array instance:

[   {      "precision": "zip",      "Latitude":  37.7668,      "Longitude": -122.3959,      "Address":   "",      "City":      "SAN FRANCISCO",      "State":     "CA",      "Zip":       "94107",      "Country":   "US"   },   {      "precision": "zip",      "Latitude":  37.371991,      "Longitude": -122.026020,      "Address":   "",      "City":      "SUNNYVALE",      "State":     "CA",      "Zip":       "94085",      "Country":   "US"   }]

4. JSON parsing case
(1) parsing one of the objects:

String jsonString ={"url":http://www.cnblogs.com/qianxudetianxia};
// Resolution method: jsonobject demojson = new jsonobject (jsonstring );
String url = demoJson.getString("url");

(2) parsing object 2:

String jsonstring = {"name": "android", "version": "beta1.0"}; // resolution method: jsonobject demojson = new jsonobject (jsonstring); string name = demojson. getstring ("name"); string version = demojson. getstring ("version"); system. out. println ("name:" + name + ", version:" + version );

(3). parse one of the arrays:

String jsonString ={"number":[1,2,3]};
// Resolution method: jsonobject demojson = new jsonobject (jsonstring); jsonarray numberlist = demojson. getjsonarray ("Number ");for(int i=0; i<numberList.length(); i++){     // Because the type in the array is int, It is getint. Other getstring and getlong are used in the same way.    System.out.println(numberList.getInt(i)); }

(4). parse array 2:

String jsonstring = {"Number": [[1], [2], [3]}; // resolution method: // nested array traversal jsonobject demojson = new jsonobject (jsonstring); jsonarray numberlist = demojson. getjsonarray ("Number"); For (INT I = 0; I <numberlist. length (); I ++) {// obtain the array system. out. println (numberlist. getjsonarray (I ). getint (0 ));}

(5). parse object and array:

String jsonstring = {"mobile": [{"name": "android" },{ "name": "iPhone"}]}; // resolution method: jsonobject demojson = new jsonobject (jsonstring); jsonarray numberlist = demojson. getjsonarray ("mobile"); For (INT I = 0; I <numberlist. length (); I ++) {system. out. println (numberlist. getjsonobject (I ). getstring ("name "));}

(6). Use opttype:

In the preceding example, when GetType is used, an exception is thrown when the node cannot be found.
If opttype is used and no node is found, null or default value is returned.

// No URL node, throwing an exception string url = demojson. getstring ("url"); // No URL node. null is returned. If it is of the basic type, the default value string url = demojson is returned. optstring ("url ");

(7). UTF-8 BOM header causes JSON parsing exceptions
When the JSON file is saved as UTF-8, the BOM Header "Ef bb ef" is generated at the beginning of the text (which can be viewed only when it is opened using a hexadecimal tool ).
There are two solutions:
A. Use ultraedit to open the JSON file, save as, select the format of UTF-8, no Bom header, if not, open in notepad, save as UTF-8, try multiple times on it.
B. Use code processing to intercept the JSON body content:

String jsonString = getJsonString();jsonString =jsonString.substring(jsonString.indexOf("{"),jsonString.lastIndexOf("}")+1);

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.