XStream and JSON

Source: Internet
Author: User
Tags package json xml parser

 The role of XStream XStream can convert JavaBean objects into xml! The data that the server responds to the client is usually a set of objects from the database, and we cannot directly respond to the object to the response, so we need to convert the object to XML and then respond to the client, then we need to use the XStream combination. 2 XStream Introduction In order to demonstrate the role of xstream, we need to write two classes, province and city first. City.javapublic class City {private string name;private string description; ...} Province.javapublic class Province {private String name;private list<city> cities = new arraylist<city> (); public void addcity (city) {cities.add (city);} ......} Next, we need to write a main (), create a list,list to store two province objects! Finally we convert the list into XML. Province P1 = new province ("Liaoning province");p 1.addCity ("Shenyang", "Shenyang");p 1.addCity (New City ("Dalian", "Dalian")); Province P2 = new Province ("Jilin Province");p 2.addCity (New City ("Changchun", "Changchen"));p 2.addCity (New City ("Baicheng", "Baicheng")); list<province> list = new arraylist<province> (), List.add (p1), List.add (p2), 2.1 XStream related jar package we can go to http:// xstream.codehaus.org/address to download the XStream installation package! XStream's required jar package:? Core Jar Package: Xstream-1.4.7.jar;? must be dependent on package: xpp3_min-1.1.4c (XML Pull Parser, a fast XML parser); 2.2 Using XStream to convert a Java object to XML the following is the use of XStream to convert list toCode FOR XML: XStream XStream = new XStream (); String s = xstream.toxml (list); System.out.println (s); <list > <cn.itcast.xstream.demo1.province > <name > Liaoning </name> <cit ies > <cn.itcast.xstream.demo1.city > <name > Shenyang </name> <description >shenyan g</description> </cn.itcast.xstream.demo1.City> <cn.itcast.xstream.demo1.City> <name > Dalian </name> <description>dalian</description> </cn.itcast.xstream.demo1.City> &lt ;/cities> </cn.itcast.xstream.demo1.Province> <cn.itcast.xstream.demo1.Province> <name> Jilin Province </name> <cities> <cn.itcast.xstream.demo1.City> <name> Changchun </name> <de Scription>changchen</description> </cn.itcast.xstream.demo1.City> <cn.itcast.xstream.demo1.cit y> <name> Baicheng </name> <description>baicheng</description> </cn.itcast.xstream.demo1.City> </cities> </cn.itcast.xstream.demo1.Province>< /list> that is, XStream generates an XML document based on the object name, class name, and property name! 2.3 Alias usage as you can see, in the generated XML, the element name corresponding to the class name contains the package name part, which is not nice! To customize the generated element name, you need to use XStream to provide an alias for the class name: Xstream.alias ("Province", Province.class);  Xstream.alias ("China", List.class);  Xstream.alias ("City", City.class); <china> <province> <name> Liaoning </name> <cities> <city> <name> Shenyang </name> <description>shenyang</description> </city> <city> <nam e> Dalian </name> <description>dalian</description> </city> </cities> </prov Ince> <province> <name> Jilin Province </name> <cities> <city> <name> Changchun </n ame> <description>changchen</description> </city> <city> <name> Baicheng </name> <d escription>baicheng</description> </city> </cities> </province></china>2.4 yuan Elements into element properties for example, we need to turn <province> sub-elements <name> into: <province name= "" > style, then you need to call the following method: Xstream.useattributefor ( Province.class, "name");        <china> <province name= "Liaoning Province" > <cities> <city> <name> Shenyang </name>        <description>shenyang</description> </city> <city> <name> Dalian </name> <description>dalian</description> </city> </cities> </province> <province Name= "Jilin Province" > <cities> <city> <name> Changchun </name> <description>changchen& lt;/description> </city> <city> <name> Baicheng </name> <description>baic heng</description> </city> </cities> </province></china>2.5 Remove set attribute corresponding element everyone may have found out because p The Ronvice class has aCities members, so the <cities> element is generated, but this element doesn't make much sense to the XML document, so we want to remove it! Xstream.addimplicitcollection (Province.class, "cities"); <china> <province name= "Liaoning Province" > <city> <name> Shenyang </name> <description>sheny ang</description> </city> <city> <name> Dalian </name> &LT;DESCRIPTION&GT;DALIAN&L t;/description> </city> </province> <province name= "Jilin Province" > <city> <name> Changchun &lt ;/name> <description>changchen</description> </city> <city> <name> Baicheng </ Name> <description>baicheng</description> </city> </province></china>2.6 Let the members of the class not be born into the corresponding XML element so far, we are each class, each member has a corresponding element (or attribute) exists, but sometimes we do not want members of certain classes to appear in the corresponding XML document, for example, we do not want the description members of the City class to appear in the XML document,  The following methods can be used: Xstream.omitfield (city.class, "description");  <china> <province name= "Liaoning Province" > <city> <name> Shenyang </name> </city>  <city> <name> Dalian </name> </city> </province> <province name= "Jilin Province" > <ci   ty> <name> Changchun </name> </city> <city> <name> Baicheng </name> </city> </province></china>json1 What is Jsonjson (JavaScript Object Notation) is a lightweight data interchange format. JSON is a string representation of a JavaScript object, such as a JSON-formatted string that can be sent to the client Javascript,javascript in a servlet to execute the string and get a JavaScript object. XML can also be used to tong great data exchange, previously learned to send XML to JavaScript in the servlet, and then JavaScript to parse the XML. 2 JSON object syntax JSON syntax:? data in a name/value pair? Data is separated by commas? Curly brackets Save the object? square brackets Save the array var person = {"Name": "Zhangsan", "Age": "+", "Sex": "Male"};alert (  Person.name + "," + Person.age + "," + person.sex); Note that the key is also in double quotes! JSON value: Number (integer or floating point)? The string (in double quotation marks)? The logical value (TRUE or false)? The array (in square brackets)? The object (in curly brackets)? Nullvar person = {"Name": "Zhangsan", "Age": "18", " Sex ":" Male "," hobby ": [" CF "," SJ "," DDM "]};alert (Person.name +", "+ Person.age +", "+ Person.sex +", "+ person.hobby ); Json object with method: var person = {"Name": "Zhangsan", "GetName": function() {return this.name;}}; alert (person.name); alert (Person.getname ()); 3 JSON vs. xml comparison? readability: XML wins; decoding difficulty: JSON itself is the JS object (home combat), so much simpler; Popularity: XML has been popular for many years, but in the Ajax world, JSON is more popular. 4 Convert Java objects to JSON objects the Json-lib gadget provided by Apache, which makes it easy to use the Java language to create JSON strings. You can also convert the JavaBean to a JSON string. The core jar package for the 4.1 json-lib core jar package Json-lib is:? Json-lib.jarjson-lib's dependent jar package:? Commons-lang.jar?commons-beanutils.jar? The core class in commons-logging.jar?commons-collections.jar?ezmorph.jar4.2 Json-lib has only two core classes in Json-lib:? Jsonobject;? The jsonarray;4.1 Jsonobjectjsonobject class itself is a map, so it's convenient to learn it. Jsonobject Jo = new Jsonobject (), Jo.put ("name", "Zhangsan"), Jo.put ("Age", "all"), Jo.put ("Sex", "male"); System.out.println (Jo.tostring ()); person person = new Person ("LiSi", "female"); Jsonobject Jo = jsonobject.fromobject (person); System.out.println (Jo.tostring ()); Map map = new HashMap (), Map.put ("name", "Wangwu"), Map.put ("Age", "Bayi"), Map.put ("Sex", "male"); Jsonobject Jo = jsonobject.fromobject (map); System.out.println (Jo.tostring ()); String XML = "<person><name>zhaoliu</name><age>59</age><sex>female</sex></person> "; XMLSerializer serial = new XMLSerializer (); Jsonobject Jo = (jsonobject) serial.read (XML); System.out.println (Jo.tostring ()); 4.2 Jsonarrayjsonarray itself is a list, so it is convenient to use. Jsonarray ja = new Jsonarray (); person P1 = new Person ("Zhangsan", "male"); person P2 = new Person ("LiSi", "female"), Ja.add (p1); Ja.add (p2); System.out.println (Ja.tostring ()); person P1 = new Person ("Zhangsan", "male"); person P2 = new Person ("LiSi", "female"); list<person> list = new arraylist<person> (); List.add (p1); List.add (p2); Jsonarray ja = jsonarray.fromobject (list); System.out.println (Ja.tostring ()); person P1 = new Person ("Zhangsan", "male"); person P2 = new Person ("LiSi", "female"); person[] persons = {P1, p2}; Jsonarray ja = jsonarray.fromobject (persons); System.out.println (Ja.tostring ()); 5 JS explanation The server sends over the JSON string the server sends over the JSON string, which the client needs to parse. At this point the client needs to execute the JSON string using the eval () Method! Note, however, that the eval () method must enclose the JSON string in a pair of parentheses when it executes the JSON. var json = "{\" name\ ": \" zhangsan\ ", \" age\ ": \" 18\ ", \" sex\ ": \" Male\ "}", var person = eval ("(" + JSON + ")"), Alert (Person.name + ", "+ Person.age +", "+ person.sex);

  

XStream and JSON

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.