Java Object Representation 2:xstream implementing XML for an object

Source: Internet
Author: User
Tags serialization

The previous article referred to the use of Java native serialization to represent an object. Summarize the pros and cons of this method of object representation:

1, Pure Java environment in this way can work well, because it comes with Java, and does not require third-party jar package support

2. In a multi-lingual environment, it is difficult to restore results in other languages after storing in a Java serialization format

3, occupies a large number of bytes, and serialization, deserialization efficiency is not high

As mentioned earlier, objects represent a variety of ways, and serialization is just one of them. The purpose of representing an object is nothing more than an object <---->io mutual understanding, as to how to know, there are many choices. In addition to the previously mentioned serialization, you can also choose to JSON and XML the data. There are now more useful serialization tools, such as Google's protobuf. This article mainly wants to write about the XML of the object, using XStream. As for why choose to write XStream, because work, hehe.

Use XStream to represent an object

XStream is a tool for translating between Java objects and XML, and there is nothing special about it, XStream provides support for the direct conversion of all types, arrays, collections, and so on. The core class in XStream is the XStream class, which is generally sufficient for familiarity with this class. Using XStream requires two third-party jar packages, the Xstream-1.4.jar and kxml2. Jarused in my project. At first I was playing XStream thought only needs the previous jar package to be possible, the result runs the time various errors, therefore must pay attention here. First write the simplest program:

1PublicClassXmlobject2{3PrivateIntCount4PrivateDoublePrice5PrivateString phone;67Public Xmlobject (int count,DoublePrice, String phone)8{9This.count =count; Ten this.price = Price ;  One this.phone = phone;  The public   String toString () (), and the "  count =" + Count + " = "+ Price +", phone = "+ phone";  + }                
void Main (string[] args){new XStream ();  New Xmlobject (10.5, "ten");  5 String str = xs.toxml (XO);  System.out.println (str); 7}         

Look at the results of the operation:

<com.xrq.test.XmlObject>  <count>10</count>  <price>10.5</price>  < Phone>110</phone></com.xrq.test.xmlobject>

Yes, it's so simple, I'm going to show you an object. At this time, how to operate this str does not matter, you can use a filewriter to put this str into disk, you can also use a httpclient transmission of this string str for network communication.

Set up aliases

OK, see above this string of output, some people may be unhappy, "com.xrq.test.XmlObject" so troublesome, can you say simple point ah? Of course, and not only can you rename the object, but the properties in the object can also:

1PublicStaticvoidMain (string[] args)2{3 XStream xs =NewXStream ();4 Xmlobject XO =new Xmlobject (10.5, "ten"  Class);  6 Xs.aliasfield ("Count", Xmlobject.);  7 Xs.aliasfield ("Price", Xmlobject.);  8 Xs.aliasfield ("Phone", Xmlobject. Class, "Phone" );  Xs.toxml (XO);  System.out.println (str);                 

Look at the results of the operation:

<XmlObject>  <Count>10</Count>  <Price>10.5</Price>  <phone>110 </Phone></XmlObject>

As you can see, the object name has changed and the name of the property in the object has changed.

XStream supports arrays and collections

Previously said, XStream not only support the basic data types, but also support arrays, collections, modify the program and then look at:

1PublicClassXmlobject2{3PrivateInt[] counts;4Private list<string>phones;5Private Map<string, date>Calendar67Public Xmlobject (Int[] counts, list<string> phones, map<string, date>Calendar8{9This.counts = counts; 10 this.phones = phones ; 11 this.calendar = Calendar 12 }13 14 public String toString () 15  {16 return "Count =" + counts + ", phones =" + Phones + ", calendar =" + Calendar;17 }18}       
1PublicStaticvoidMain (string[] args)2{3Int[] counts = {10, 11, 12};4 List<string> phones =New arraylist<string>();5 Phones.add ("110");6 Phones.add ("119");7 Phones.add ("120");8 map<string, date> calendar =New Hashmap<string, date>();9 Calendar.put ("1",NewDate ());Ten Calendar.put ("2",NewDate ());One XStream xs =NewXStream ();Xmlobject XO =New Xmlobject (counts, phones, calendar); 13 xs.alias ("Xmlobject", Xmlobject. Class); 14 Xs.aliasfield ("Count", Xmlobject.); 15 Xs.aliasfield ("Phones", Xmlobject. Class, "Phones" ); 16 Xs.aliasfield ("Calendar", Xmlobject. class, "Calendar" ); 17 String str = Xs.toxml (XO);  System.out.println (str);                 

Look at the results of the operation

+ View Code

It's a little uncomfortable to see the two letters of the string and date are lowercase? It's okay, leaf out, the main function, plus these two sentences.

xs.alias("String", String.class);xs.alias("Date", Date.class);

XML into Java objects

Back to the simplest of the xmlobject, it would be easy to take a look at the conversion of XML to a Java object, using the FromXml () method. Construct an XML string yourself:

 1 public static Span style= "color: #0000ff;" >void main (string[] args) 2 {3 XStream xs = new XStream (); 4 String xmlstr = "<com.xrq.test.XmlObject><count>10</count>< Price>10.5</price><phone>110</phone></com.xrq.test.xmlobject> " 5 xmlobject xo = (Xmlobject) xs.fromxml (XMLSTR); 6  System.out.println (XO);                 

The result of the operation is not affixed, is xmlobject three attributes of ToString () just. Note that there is no alias in the "com.xrq.test.XmlObject", if directly with the "Xmlobject" will be reported Com.thoughtworks.xstream.mapper.CannotResolveClassException "this exception. The solution is simple, the 5th line is preceded by Xs.alias ("Xmlobject", Xmlobject.class);

Postscript

The article mainly wrote about the use of xstream, generally speaking, xstream used to this extent is enough. XStream is very easy to use, and the data after XML is very readable. On GitHub, however, I saw an article https://github.com/eishay/jvm-serializers/wiki that the downside of XML is that it is less efficient to parse, and that for readability, XML introduces a Some of the redundant text information, resulting in a certain amount of space overhead. However, in any case, it is recommended to use XStream in a scenario where the operation is not very large.

Java Object Representation 2:xstream implementing XML for an object

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.