English 中文(简体)
XStream - Annotations
  • 时间:2024-09-17

XStream - Annotations


Previous Page Next Page  

XStream supports annotations similarly pke automatic configuration instead of coding. In the previous chapter, we ve seen the following configurations in code.

xstream.apas("student", Student.class);
xstream.apas("note", Note.class);

xstream.useAttributeFor(Student.class, "studentName");
xstream.apasField("name", Student.class, "studentName");
xstream.addImppcitCollection(Student.class, "notes");

The following code snippet illustrates the use of annotations to do the same work in a much easier way.

@XStreamApas("student")   //define class level apas
class Student {

   @XStreamApas("name")   //define field level apas
   @XStreamAsAttribute     //define field as attribute
   private String studentName;
   
   @XStreamImppcit        //define pst as an imppcit collection
   private List<Note> notes = new ArrayList<Note>();
   
   @XStreamOmitField       //omit a field to not to be a part of XML
   private int type;
}

Let us test the above annotation using 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 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.XStreamApas;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImppcit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
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.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;
   }

   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 String studentName;

   @XStreamImppcit
   private List<Note> notes = new ArrayList<Note>();

   pubpc Student(String name) {
      this.studentName = name;
   }

   pubpc void addNote(Note note) {
      notes.add(note);
   }

   pubpc String getName() {
      return studentName;
   }

   pubpc List<Note> getNotes() {
      return notes;
   }
   
   @XStreamOmitField		
   private int type;

   pubpc int getType() {
      return type;
   }

   pubpc void setType(int type) {
      this.type = type;
   }
}

@XStreamApas("note")
class Note {
   private String title;
   private String description;

   pubpc Note(String title, String description) {
      this.title = title;
      this.description = description;
   }

   pubpc String getTitle() {
      return title;
   }

   pubpc String getDescription() {
      return description;
   }     
}

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">
   <note>
      <title>first</title>
      <description>My first assignment.</description>
   </note>

   <note>
      <title>second</title>
      <description>My Second assignment.</description>
   </note>
</student>

In order to instruct the XStream framework to process annotation, you need to add the following command before seriapzing xml.

xstream.processAnnotations(Student.class);		

Or

xstream.autodetectAnnotations(true);
Advertisements