XStream - Panduan Cepat
XStream adalah pustaka berbasis Java sederhana untuk membuat serial objek Java ke XML dan sebaliknya.
fitur
Easy to use - XStream API menyediakan fasad tingkat tinggi untuk menyederhanakan kasus penggunaan umum.
No need to create mapping - XStream API menyediakan pemetaan default untuk sebagian besar objek yang akan diserialkan.
Performance - XStream cepat dan memiliki footprint memori rendah, yang cocok untuk grafik atau sistem objek besar.
Clean XML - XStream menghasilkan keluaran XML yang bersih dan ringkas yang mudah dibaca.
Object modification not required- XStream membuat serial bidang internal seperti bidang pribadi dan final, dan mendukung kelas non-publik dan dalam. Konstruktor default bukanlah persyaratan wajib.
Full object graph support - XStream memungkinkan untuk mempertahankan referensi duplikat yang ditemukan dalam model objek dan juga mendukung referensi melingkar.
Customizable conversion strategies - Strategi kustom dapat didaftarkan untuk memungkinkan kustomisasi jenis tertentu direpresentasikan sebagai XML.
Security framework - XStream memberikan kontrol yang adil atas jenis yang tidak diatur untuk mencegah masalah keamanan dengan input yang dimanipulasi.
Error messages - Ketika pengecualian terjadi karena XML cacat, ini memberikan diagnosa rinci untuk memperbaiki masalah.
Alternative output format - XStream mendukung format output lain seperti JSON dan morphing.
Penggunaan Umum
Transport - XML adalah representasi teks dari objek dan dapat digunakan untuk mengangkut objek melalui kabel independen dari teknik serialisasi / deserialisasi yang digunakan.
Persistence - Objek dapat disimpan sebagai XML dalam database dan dapat diatur / tidak diatur sesuai kebutuhan.
Configuration- XML cukup jelas dan banyak digunakan untuk mendefinisikan konfigurasi. Objek juga dapat digunakan untuk tujuan konfigurasi setelah mengubahnya menjadi representasi XML.
Unit Tests - XStream API kompatibel dengan JUnit dan dapat digunakan untuk meningkatkan pengujian unit modul aplikasi.
Dalam bab ini, kita akan membahas tentang berbagai aspek pengaturan lingkungan yang cocok untuk Java.
Pengaturan Lingkungan Lokal
Jika Anda ingin mengatur lingkungan Anda untuk bahasa pemrograman Java, maka bagian ini menjelaskan cara mengunduh dan mengatur Java di komputer Anda. Silakan ikuti langkah-langkah yang diberikan di bawah ini untuk mengatur lingkungan Java Anda.
Java SE dapat diunduh secara gratis dari tautan -
Unduh Java .
Ikuti petunjuk untuk mengunduh Java dan menjalankan .exeuntuk menginstal Java di komputer Anda. Setelah Anda menginstal Java di komputer Anda, Anda perlu mengatur variabel lingkungan agar mengarah ke direktori instalasi yang benar -
Menyiapkan Path untuk Windows 2000 / XP
Dengan asumsi Anda telah menginstal Java di direktori c: \ Program Files \ java \ jdk -
Klik kanan pada 'My Computer' dan pilih 'Properties'.
Klik tombol 'Variabel lingkungan' di bawah tab 'Lanjutan'.
Ubah variabel 'Path' sehingga juga berisi path ke Java yang dapat dieksekusi. Misalnya, jika jalur saat ini disetel ke 'C: \ WINDOWS \ SYSTEM32', ubah jalur Anda menjadi 'C: \ WINDOWS \ SYSTEM32; c: \ Program Files \ java \ jdk \ bin'.
Menyiapkan Path untuk Windows 95/98 / ME
Dengan asumsi Anda telah menginstal Java di direktori c: \ Program Files \ java \ jdk -
Edit file 'C: \ autoexec.bat' dan tambahkan baris berikut di akhir -
'SET PATH =% PATH%; C: \ Program Files \ java \ jdk \ bin'
Menyiapkan Path untuk Linux, UNIX, Solaris, FreeBSD
Variabel lingkungan PATH harus disetel agar mengarah ke tempat biner Java telah dipasang. Lihat dokumentasi shell Anda jika Anda mengalami masalah dalam melakukan ini.
Misalnya, jika Anda menggunakan bash sebagai shell Anda, maka Anda akan menambahkan baris berikut di akhir '.bashrc: export PATH = / path / to / java: $ PATH'
Editor Java Populer
Untuk menulis program Java, Anda memerlukan editor teks. Ada IDE yang lebih canggih yang tersedia di pasaran. Tetapi untuk saat ini, Anda dapat mempertimbangkan salah satu dari yang berikut -
Notepad - Di Windows, Anda dapat menggunakan editor teks sederhana seperti Notepad (Disarankan untuk tutorial ini) atau TextPad.
Netbeans - Ini adalah IDE Java yang gratis dan dapat diunduh dari https://www.netbeans.org/index.html.
Eclipse - Ini juga merupakan Java IDE yang dikembangkan oleh komunitas open-source eclipse dan dapat diunduh dari https://www.eclipse.org/.
Unduh XStream Archive
Unduh versi terbaru file jar XStream dari xstream-1.4.7.jar. Pada saat menulis tutorial ini, kami telah mengunduh xstream-1.4.7.jar dan menyalinnya ke folder C: \> XStream.
OS | Nama arsip |
---|---|
Windows | xstream-1.4.7.jar |
Linux | xstream-1.4.7.jar |
Mac | xstream-1.4.7.jar |
Setel Lingkungan XStream
Mengatur XStream_HOMEvariabel lingkungan untuk menunjuk ke lokasi direktori dasar tempat jar xstream disimpan di komputer Anda. Tabel berikut menunjukkan cara mengatur lingkungan XStream di Windows, Linux, dan Mac, dengan asumsi kita telah mengekstrak xstream-1.4.7.jar di folder XStream.
Sr.No. | OS & Deskripsi |
---|---|
1 | Windows Setel variabel lingkungan XStream_HOME ke C: \ XStream |
2 | Linux ekspor XStream_HOME = / usr / local / XStream |
3 | Mac ekspor XStream_HOME = / Library / XStream |
Setel Variabel CLASSPATH
Mengatur CLASSPATHvariabel lingkungan untuk menunjuk ke lokasi jar XStream. Tabel berikut menunjukkan cara menyetel variabel CLASSPATH pada sistem Windows, Linux, dan Mac, dengan asumsi kami telah menyimpan xstream-1.4.7.jar di folder XStream.
Sr.No. | OS & Deskripsi |
---|---|
1 | Windows Setel variabel lingkungan CLASSPATH ke% CLASSPATH%;% XStream_HOME% \ xstream-1.4.7.jar; |
2 | Linux ekspor CLASSPATH = $ CLASSPATH: $ XStream_HOME / xstream-1.4.7.jar; |
3 | Mac ekspor CLASSPATH = $ CLASSPATH: $ XStream_HOME / xstream-1.4.7.jar; |
Sebelum masuk ke detail pustaka XStream, mari kita lihat aplikasi beraksi. Dalam contoh ini, kami telah membuat kelas Siswa dan Alamat. Kita akan membuat objek siswa dan kemudian membuatnya menjadi String XML. Kemudian de-serialisasi string XML yang sama untuk mendapatkan objek siswa kembali.
Buat file kelas java bernama XStreamTester di C: \> XStream_WORKSPACE.
File: XStreamTester.java
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.io.xml.StaxDriver;
public class XStreamTester {
public static void main(String args[]) {
XStreamTester tester = new XStreamTester();
XStream xstream = new XStream(new StaxDriver());
Student student = tester.getStudentDetails();
//Object to XML Conversion
String xml = xstream.toXML(student);
System.out.println(formatXml(xml));
//XML to Object Conversion
Student student1 = (Student)xstream.fromXML(xml);
System.out.println(student1);
}
private Student getStudentDetails() {
Student student = new Student();
student.setFirstName("Mahesh");
student.setLastName("Parashar");
student.setRollNo(1);
student.setClassName("1st");
Address address = new Address();
address.setArea("H.No. 16/3, Preet Vihar.");
address.setCity("Delhi");
address.setState("Delhi");
address.setCountry("India");
address.setPincode(110012);
student.setAddress(address);
return student;
}
public static String formatXml(String xml) {
try {
Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.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());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
} catch(Exception e) {
return xml;
}
}
}
class Student {
private int rollNo;
private String firstName;
private String lastName;
private String className;
private Address address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Student [ ");
stringBuilder.append("\nfirstName: ");
stringBuilder.append(firstName);
stringBuilder.append("\nlastName: ");
stringBuilder.append(lastName);
stringBuilder.append("\nrollNo: ");
stringBuilder.append(rollNo);
stringBuilder.append("\nclassName: ");
stringBuilder.append(className);
stringBuilder.append("\naddress: ");
stringBuilder.append(address);
stringBuilder.append(" ]");
return stringBuilder.toString();
}
}
class Address {
private String area;
private String city;
private String state;
private String country;
private int pincode;
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\nAddress [ ");
stringBuilder.append("\narea: ");
stringBuilder.append(area);
stringBuilder.append("\ncity: ");
stringBuilder.append(city);
stringBuilder.append("\nstate: ");
stringBuilder.append(state);
stringBuilder.append("\ncountry: ");
stringBuilder.append(country);
stringBuilder.append("\npincode: ");
stringBuilder.append(pincode);
stringBuilder.append(" ]");
return stringBuilder.toString();
}
}
Verify the Result
Kompilasi kelas menggunakan javac kompiler sebagai berikut -
C:\XStream_WORKSPACE>javac XStreamTester.java
Sekarang jalankan XStreamTester untuk melihat hasilnya -
C:\XStream_WORKSPACE>java XStreamTester
Verify the output as follows
<?xml version = "1.0" encoding = "UTF-8"?>
<Student>
<firstName>Mahesh</firstName>
<lastName>Parashar</lastName>
<rollNo>1</rollNo>
<className>1st</className>
<address>
<area>H.No. 16/3, Preet Vihar.</area>
<city>Delhi</city>
<state>Delhi</state>
<country>India</country>
<pincode>110012</pincode>
</address>
</Student>
Student [
firstName: Mahesh
lastName: Parashar
rollNo: 1
className: 1st
address:
Address [
area: H.No. 16/3, Preet Vihar.
city: Delhi
state: Delhi
country: India
pincode: 110012
]
]
Langkah-langkah untuk Diingat
Berikut adalah langkah-langkah penting untuk dipertimbangkan di sini.
Langkah 1: Buat Objek XStream
Buat objek XStream dengan meneruskannya StaxDriver. StaxDriver menggunakan parser tarik Stax (tersedia dari java 6) dan merupakan parser xml cepat.
XStream xstream = new XStream(new StaxDriver());
Langkah 2: Serialisasi Objek ke XML
Gunakan metode toXML () untuk mendapatkan representasi string XML dari objek.
//Object to XML Conversion
String xml = xstream.toXML(student);
Langkah 3: De-serialisasi XML untuk Mendapatkan Objek
Gunakan metode fromXML () untuk mendapatkan objek dari XML.
//XML to Object Conversion
Student student1 = (Student)xstream.fromXML(xml);
Aliasing adalah teknik untuk menyesuaikan XML yang dihasilkan atau menggunakan XML berformat tertentu menggunakan XStream. Anggaplah format XML berikut akan digunakan untuk membuat serial / de-serialisasi objek Student.
<student name = "Suresh">
<note>
<title>first</title>
<description>My first assignment.</description>
</note>
<note>
<title>second</title>
<description>My second assignment.</description>
</note>
</student>
Berdasarkan format XML di atas, mari kita buat kelas model.
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName() {
return studentName;
}
public List<Note> getNotes() {
return notes;
}
}
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
}
Mari kita uji serialisasi objek di atas menggunakan XStream.
Buat file kelas java bernama XStreamTester di C: \> XStream_WORKSPACE \ com \ tutorialspoint \ xstream.
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
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.io.xml.StaxDriver;
public class XStreamTester {
public static void main(String args[]) {
XStreamTester tester = new XStreamTester();
XStream xstream = new XStream(new StaxDriver());
Student student = tester.getStudentDetails();
//Object to XML Conversion
String xml = xstream.toXML(student);
System.out.println(formatXml(xml));
}
private Student getStudentDetails() {
Student student = new Student("Mahesh");
student.addNote(new Note("first","My first assignment."));
student.addNote(new Note("second","My Second assignment."));
return student;
}
public static String formatXml(String xml) {
try {
Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.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());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
} catch(Exception e) {
return xml;
}
}
}
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName() {
return studentName;
}
public List<Note> getNotes() {
return notes;
}
}
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
}
Verify the Result
Kompilasi kelas menggunakan javac kompiler sebagai berikut -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
Sekarang jalankan XStreamTester untuk melihat hasilnya -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
Verifikasi output sebagai berikut -
<?xml version = "1.0" encoding = "UTF-8"?>
<com.tutorialspoint.xstream.Student>
<studentName>Mahesh</studentName>
<notes>
<com.tutorialspoint.xstream.Note>
<title>first</title>
<description>My first assignment.</description>
</com.tutorialspoint.xstream.Note>
<com.tutorialspoint.xstream.Note>
<title>second</title>
<description>My Second assignment.</description>
</com.tutorialspoint.xstream.Note>
</notes>
</com.tutorialspoint.xstream.Student>
Pada hasil di atas, nama objek siswa memenuhi syarat. Untuk menggantinya sebagai tag siswa, ikuti bagian selanjutnya.
Aliasing Kelas
Aliasing Bidang
Aliasing Koleksi Implisit
Atribut Aliasing
Paket Aliasing
XStream mendukung anotasi yang mirip seperti konfigurasi otomatis daripada pengkodean. Di bab sebelumnya, kita telah melihat konfigurasi berikut dalam kode.
xstream.alias("student", Student.class);
xstream.alias("note", Note.class);
xstream.useAttributeFor(Student.class, "studentName");
xstream.aliasField("name", Student.class, "studentName");
xstream.addImplicitCollection(Student.class, "notes");
Cuplikan kode berikut mengilustrasikan penggunaan anotasi untuk melakukan pekerjaan yang sama dengan cara yang jauh lebih mudah.
@XStreamAlias("student") //define class level alias
class Student {
@XStreamAlias("name") //define field level alias
@XStreamAsAttribute //define field as attribute
private String studentName;
@XStreamImplicit //define list as an implicit collection
private List<Note> notes = new ArrayList<Note>();
@XStreamOmitField //omit a field to not to be a part of XML
private int type;
}
Mari kita uji penjelasan di atas menggunakan XStream.
Buat file kelas java bernama XStreamTester di C: \> XStream_WORKSPACE \ com \ tutorialspoint \ xstream.
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
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.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class XStreamTester {
public static void main(String args[]) {
XStreamTester tester = new XStreamTester();
XStream xstream = new XStream(new StaxDriver());
Student student = tester.getStudentDetails();
xstream.processAnnotations(Student.class);
//Object to XML Conversion
String xml = xstream.toXML(student);
System.out.println(formatXml(xml));
}
private Student getStudentDetails() {
Student student = new Student("Mahesh");
student.addNote(new Note("first","My first assignment."));
student.addNote(new Note("second","My Second assignment."));
student.setType(1);
return student;
}
public static String formatXml(String xml) {
try {
Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.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());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
} catch(Exception e) {
return xml;
}
}
}
@XStreamAlias("student")
class Student {
@XStreamAlias("name")
@XStreamAsAttribute
private String studentName;
@XStreamImplicit
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName() {
return studentName;
}
public List<Note> getNotes() {
return notes;
}
@XStreamOmitField
private int type;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
@XStreamAlias("note")
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
}
Verifikasi Hasilnya
Kompilasi kelas menggunakan javac kompiler sebagai berikut -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
Sekarang jalankan XStreamTester untuk melihat hasilnya -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
Verifikasi output sebagai berikut -
<?xml version = "1.0" encoding = "UTF-8"?>
<student name = "Mahesh">
<note>
<title>first</title>
<description>My first assignment.</description>
</note>
<note>
<title>second</title>
<description>My Second assignment.</description>
</note>
</student>
Untuk menginstruksikan kerangka XStream untuk memproses anotasi, Anda perlu menambahkan perintah berikut sebelum membuat serial xml.
xstream.processAnnotations(Student.class);
Atau
xstream.autodetectAnnotations(true);
Konverter XStream adalah komponen kunci dari perpustakaan XStream, yang bertanggung jawab untuk mengonversi objek ke XML dan sebaliknya. XStream menyediakan banyak konverter untuk tipe umum seperti primitif, String, File, Koleksi, array, dan Tanggal.
Menggunakan Konverter
Mari kita menggunakan SingleValueConvertor yang tujuannya adalah untuk mengubah objek menjadi string tunggal. Kami akan menggunakan SingleValueConvertor untuk menulis objek sebagai string atribut.
Buat Konverter
class NameConverter implements SingleValueConverter {
public Object fromString(String name) {
String[] nameparts = name.split(",");
return new Name(nameparts[0], nameparts[1]);
}
public String toString(Object name) {
return ((Name)name).getFirstName() + "," + ((Name)name).getLastName();
}
public boolean canConvert(Class type) {
return type.equals(Name.class);
}
}
Daftarkan Konverter
xstream.registerConverter(new NameConverter());
Contoh tanpa Konverter
Mari kita uji kode tanpa konverter di XStream.
Buat file kelas java bernama XStreamTester di C: \> XStream_WORKSPACE \ com \ tutorialspoint \ xstream.
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.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class XStreamTester {
public 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;
}
public static String formatXml(String xml) {
try {
Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.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());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
} catch(Exception e) {
return xml;
}
}
}
@XStreamAlias("student")
class Student {
@XStreamAlias("name")
@XStreamAsAttribute
private Name studentName;
public Student(String firstName, String lastName) {
this.studentName = new Name(firstName, lastName);
}
public Name getName() {
return studentName;
}
}
class Name {
private String firstName;
private String lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
Verify the Result
Kompilasi kelas menggunakan javac kompiler sebagai berikut -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
Sekarang jalankan XStreamTester untuk melihat hasilnya -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
Verifikasi output sebagai berikut -
<?xml version = "1.0" encoding = "UTF-8"?>
<student>
<name>
<firstName>Mahesh</firstName>
<lastName>Parashar</lastName>
</name>
</student>
Contoh dengan Konverter
Sekarang mari kita uji kode dengan konverter di XStream.
Buat file kelas java bernama XStreamTester di C: \> XStream_WORKSPACE \ com \ tutorialspoint \ xstream.
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.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class XStreamTester {
public 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;
}
public static String formatXml(String xml) {
try {
Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.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());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
} catch(Exception e) {
return xml;
}
}
}
@XStreamAlias("student")
class Student {
@XStreamAlias("name")
@XStreamAsAttribute
private Name studentName;
public Student(String firstName, String lastName) {
this.studentName = new Name(firstName, lastName);
}
public Name getName() {
return studentName;
}
}
class Name {
private String firstName;
private String lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
class NameConverter implements SingleValueConverter {
public Object fromString(String name) {
String[] nameparts = name.split(",");
return new Name(nameparts[0], nameparts[1]);
}
public String toString(Object name) {
return ((Name)name).getFirstName() + "," + ((Name)name).getLastName();
}
public boolean canConvert(Class type) {
return type.equals(Name.class);
}
}
Verify the Result
Kompilasi kelas menggunakan javac kompiler sebagai berikut -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
Sekarang jalankan XStreamTester untuk melihat hasilnya -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
Verifikasi output sebagai berikut -
<?xml version = "1.0" encoding = "UTF-8"?>
<student name = "Mahesh,Parashar"/>
Konverter Kustom
XStream menyediakan implementasi alternatif java.io.ObjectInputStream dan java.io.ObjectOutputStream sehingga aliran objek dapat diserialisasi atau dideserialisasi dari XML. Ini sangat berguna ketika kumpulan objek yang besar akan diproses, menyimpan satu objek dalam memori pada satu waktu.
Sintaks: createObjectOutputStream ()
ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream(
new FileOutputStream("test.txt"));
Sintaks: createObjectInputStream ()
ObjectInputStream objectInputStream = xstream.createObjectInputStream(
new FileInputStream("test.txt"));
Mari kita sekarang menguji kode dengan aliran objek di XStream.
Buat file kelas java bernama XStreamTester di C: \> XStream_WORKSPACE \ com \ tutorialspoint \ xstream.
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class XStreamTester {
public static void main(String args[]) {
XStreamTester tester = new XStreamTester();
XStream xstream = new XStream(new StaxDriver());
xstream.autodetectAnnotations(true);
Student student1 = new Student("Mahesh","Parashar");
Student student2 = new Student("Suresh","Kalra");
Student student3 = new Student("Ramesh","Kumar");
Student student4 = new Student("Naresh","Sharma");
try {
ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream(
new FileOutputStream("test.txt"));
objectOutputStream.writeObject(student1);
objectOutputStream.writeObject(student2);
objectOutputStream.writeObject(student3);
objectOutputStream.writeObject(student4);
objectOutputStream.writeObject("Hello World");
objectOutputStream.close();
ObjectInputStream objectInputStream = xstream.createObjectInputStream(
new FileInputStream("test.txt"));
Student student5 = (Student)objectInputStream.readObject();
Student student6 = (Student)objectInputStream.readObject();
Student student7 = (Student)objectInputStream.readObject();
Student student8 = (Student)objectInputStream.readObject();
String text = (String)objectInputStream.readObject();
System.out.println(student5);
System.out.println(student6);
System.out.println(student7);
System.out.println(student8);
System.out.println(text);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
@XStreamAlias("student")
class Student {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return "Student [ firstName: "+firstName+", lastName: "+ lastName+ " ]";
}
}
Verifikasi Hasilnya
Kompilasi kelas menggunakan javac kompiler sebagai berikut -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
Sekarang jalankan XStreamTester untuk melihat hasilnya -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
Verifikasi output sebagai berikut -
Student [ firstName: Mahesh, lastName: Parashar ]
Student [ firstName: Suresh, lastName: Kalra ]
Student [ firstName: Ramesh, lastName: Kumar ]
Student [ firstName: Naresh, lastName: Sharma ]
Hello World
Lihat konten test.txt yang ada di folder C: \> XStream_WORKSPACE \ com \ tutorialspoint \ xstream.
<?xml version = "1.0" ?>
<object-stream>
<student>
<firstName>Mahesh</firstName>
<lastName>Parashar</lastName>
</student>
<student>
<firstName>Suresh</firstName>
<lastName>Kalra</lastName>
</student>
<student>
<firstName>Ramesh</firstName>
<lastName>Kumar</lastName>
</student>
<student>
<firstName>Naresh</firstName>
<lastName>Sharma</lastName>
</student>
<string>Hello World</string>
</object-stream>
XStream mendukung JSON dengan menginisialisasi objek XStream dengan driver yang sesuai. XStream saat ini mendukung JettisonMappedXmlDriver dan JsonHierarchicalStreamDriver.
Sekarang mari kita uji kode dengan penanganan json di XStream.
Buat file kelas java bernama XStreamTester di C: \> XStream_WORKSPACE \ com \ tutorialspoint \ xstream.
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.Writer;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;
public class XStreamTester {
public static void main(String args[]) {
XStreamTester tester = new XStreamTester();
XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
Student student = new Student("Mahesh","Parashar");
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("student", Student.class);
System.out.println(xstream.toXML(student));
}
}
@XStreamAlias("student")
class Student {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return "Student [ firstName: "+firstName+", lastName: "+ lastName+ " ]";
}
}
Verifikasi Hasilnya
Kompilasi kelas menggunakan javac kompiler sebagai berikut -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
Sekarang jalankan XStreamTester untuk melihat hasilnya -
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
Verifikasi output sebagai berikut -
{
"firstName": "Mahesh",
"lastName": "Parashar"
}