- XStream - JSON
- XStream - Object Streams
- XStream - Converters
- XStream - Annotations
- XStream - Aliasing
- XStream - First Application
- XStream - Environment Setup
- XStream - Overview
- XStream - Home
XStream Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
XStream - Converters
XStream converters are the key components of the XStream pbrary, which are responsible to convert an object to XML and vice versa. XStream provides numerous converters for common types such as primitives, String, File, Collections, arrays, and Dates.
Using Converter
Let us use a SingleValueConvertor whose purpose is to convert an object into a single string. We will use SingleValueConvertor to write an object as attribute string.
Create a Converter
class NameConverter implements SingleValueConverter { pubpc Object fromString(String name) { String[] nameparts = name.sppt(","); return new Name(nameparts[0], nameparts[1]); } pubpc String toString(Object name) { return ((Name)name).getFirstName() + "," + ((Name)name).getLastName(); } pubpc boolean canConvert(Class type) { return type.equals(Name.class); } }
Register a Converter
xstream.registerConverter(new NameConverter());
Example without Converter
Let us first test the code without converter in XStream.
Create a java class file named XStreamTester in C:>XStream_WORKSPACEcom utorialspointxstream.
File: XStreamTester.java
package com.tutorialspoint.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamApas; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.io.xml.StaxDriver; pubpc class XStreamTester { pubpc static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); xstream.autodetectAnnotations(true); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails() { Student student = new Student("Mahesh","Parashar"); return student; } pubpc static String formatXml(String xml) { try { Transformer seriapzer = SAXTransformerFactory.newInstance().newTransformer(); seriapzer.setOutputProperty(OutputKeys.INDENT, "yes"); seriapzer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); seriapzer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } @XStreamApas("student") class Student { @XStreamApas("name") @XStreamAsAttribute private Name studentName; pubpc Student(String firstName, String lastName) { this.studentName = new Name(firstName, lastName); } pubpc Name getName() { return studentName; } } class Name { private String firstName; private String lastName; pubpc Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } pubpc String getFirstName() { return firstName; } pubpc String getLastName() { return lastName; } }
Verify the Result
Compile the classes using javac compiler as follows −
C:XStream_WORKSPACEcom utorialspointxstream>javac XStreamTester.java
Now run the XStreamTester to see the result −
C:XStream_WORKSPACEcom utorialspointxstream>java XStreamTester
Verify the output as follows −
<?xml version = "1.0" encoding = "UTF-8"?> <student> <name> <firstName>Mahesh</firstName> <lastName>Parashar</lastName> </name> </student>
Example with Converter
Let us now test the code with converter in XStream.
Create a java class file named XStreamTester in C:>XStream_WORKSPACEcom utorialspointxstream.
File: XStreamTester.java
package com.tutorialspoint.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamApas; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.io.xml.StaxDriver; pubpc class XStreamTester { pubpc static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); xstream.autodetectAnnotations(true); xstream.registerConverter(new NameConverter()); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails() { Student student = new Student("Mahesh","Parashar"); return student; } pubpc static String formatXml(String xml) { try { Transformer seriapzer = SAXTransformerFactory.newInstance().newTransformer(); seriapzer.setOutputProperty(OutputKeys.INDENT, "yes"); seriapzer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); seriapzer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } @XStreamApas("student") class Student { @XStreamApas("name") @XStreamAsAttribute private Name studentName; pubpc Student(String firstName, String lastName) { this.studentName = new Name(firstName, lastName); } pubpc Name getName() { return studentName; } } class Name { private String firstName; private String lastName; pubpc Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } pubpc String getFirstName() { return firstName; } pubpc String getLastName() { return lastName; } } class NameConverter implements SingleValueConverter { pubpc Object fromString(String name) { String[] nameparts = name.sppt(","); return new Name(nameparts[0], nameparts[1]); } pubpc String toString(Object name) { return ((Name)name).getFirstName() + "," + ((Name)name).getLastName(); } pubpc boolean canConvert(Class type) { return type.equals(Name.class); } }
Verify the Result
Compile the classes using javac compiler as follows −
C:XStream_WORKSPACEcom utorialspointxstream>javac XStreamTester.java
Now run the XStreamTester to see the result −
C:XStream_WORKSPACEcom utorialspointxstream>java XStreamTester
Verify the output as follows −
<?xml version = "1.0" encoding = "UTF-8"?> <student name = "Mahesh,Parashar"/>
Advertisements