XStream serialize null values

前端 未结 3 476
再見小時候
再見小時候 2021-01-18 05:38

Suppose I have

class Student
{
String name;
int    age;
String teacher;
}

Then :

public class App1
{
    public static voi         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 06:07

    First of all provide the getter and setter methods in you Student class as follows:

    public class Student{
       String name;
       int age;
       String teacher;
       public void setName(String name){
           this.name = name;
       }
       public String getName(){
          return name;
       }
    .......
    ......//Like that mention other getter and setter method
    }
    

    Now, all you need to create your converter class as follows:

    public class StudentConverter implements Converter{
        public boolean canConvert(Class clazz) {
             return clazz.equals(Test.class);
        }
        public void marshal(Object value, HierarchicalStreamWriter writer,
             MarshallingContext context) {
           Student student = (Student ) value;
           writer.startNode("name");
           writer.setValue(test.getName());
           writer.endNode();
           writer.startNode("age");
           writer.setValue(test.getAge());
           writer.endNode();
           writer.startNode("teacher");
           writer.setValue("");
           writer.endNode();
       }
        public Object unmarshal(HierarchicalStreamReader reader,
             UnmarshallingContext context) {
           Student student = new Student();
           test.setName(reader.getNodeName());
           test.setAge(reader.getNodeName());
           test.setTeacher(reader.getNodeName());
           return student;
        }
    }
    
    Your main class will the like that:
    
    public class App1{
        public static void main(String args[]) {
            XStream stream = new XStream(new StaxDriver());
            Student st = new Student();
            st.setName("ABC");
            t.setAge(21);
            stream.registerConverter(new StudentConverter());
            stream.alias("student", Student.class);
            System.out.println(stream.toXML(st));
       }
    
    }
    

    Hope it's your answer....Happy Learning :)

提交回复
热议问题