- Xstream parser is used to convert java POJO to xml or json and vice-versa.
- The main benefit is we can use different parsers for different file like Stax parser.
- download jar:-
link to download xstream parser
Project Structure :-
Student Pojo Class :-
package com.sandeep.example.value.objects;
public class Student {
private String name;
private int marks;
private String course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Student Data Service:-
package com.sandeep.example.value.services;
import java.util.ArrayList;
import java.util.List;
import com.sandeep.example.value.objects.Student;
public class StudentService {
public static ListgetData(){
ListlistOfStudent =new ArrayList ();
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
student1.setName("Sandeep");
student2.setName("Surabhi");
student3.setName("Sumanta");
student4.setName("Sangeeta");
student1.setCourse("M.Tech");
student2.setCourse("MSc.");
student3.setCourse("B.Tech");
student4.setCourse("B.E.");
student1.setMarks(95);
student2.setMarks(97);
student3.setMarks(98);
student4.setMarks(45);
listOfStudent.add(student1);
listOfStudent.add(student2);
listOfStudent.add(student3);
listOfStudent.add(student4);
return listOfStudent;
}
}
Test the Parser:-
package com.sandeep.example.xstream;
import java.util.List;
import com.sandeep.example.value.objects.Student;
import com.sandeep.example.value.services.StudentService;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class TestMyXstreamParser {
public static void main(String[] args) {
//to xml conversion with alias
ListlistOfStudent=StudentService.getData();
XStream xstream = new XStream(new StaxDriver());
xstream.alias("student",com.sandeep.example.value.objects.Student.class);
String xml=xstream.toXML(listOfStudent);
System.out.println(xml);
//to json conversion with alias
XStream xstreamjson = new XStream(new JsonHierarchicalStreamDriver());
xstreamjson.setMode(XStream.NO_REFERENCES);
xstreamjson.alias("student", com.sandeep.example.value.objects.Student.class);
System.out.println(xstreamjson.toXML(listOfStudent));
}
}