简单的XML反序列化

时间:2009-12-15 21:59:02

标签: java xml xml-serialization serialization

我正在尝试Simple XML serializer。我对XML-> Java中的反序列化更感兴趣。这是我的代码作为单元测试:

import java.io.StringReader;
import java.io.StringWriter;

import junit.framework.TestCase;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class SimpleTest extends TestCase {
    public void testWriting() throws Exception {
        StringWriter writer = new StringWriter();
        Address address = new Address("1234 Main Street", "San Francisco", "CA");
        Serializer serializer = new Persister();

        serializer.write(address, writer);
        System.out.println("Wrote: " + writer.getBuffer());
    }

    public void testReading() throws Exception {
        String input = "<address street='1234 Main Street' city='San Francisco' state='CA'/>";
        Serializer serializer = new Persister();
        System.out.println("Read back: " + serializer.read(Address.class, new StringReader(input)));
    }
}

@Root
class Address {
    @Attribute(name="street")
    private final String street;

    @Attribute(name="city")
    private final String city;

    @Attribute(name="state")
    private final String state;

    public Address(@Attribute(name="street") String street, @Attribute(name="city") String city, @Attribute(name="state") String state) {
        super();
        this.street = street;
        this.city = city;
        this.state = state;
    }

    @Override
    public String toString() {
        return "Address [city=" + city + ", state=" + state + ", street=" + street + "]";
    }   
}

这样可行,但Address类中重复的@Attribute注释(在字段和构造函数参数中)看起来很难看。有没有办法:

  • 从字段名称中简单地找出属性名称?
  • 有简单的忽略序列化,以便我可以通过注释字段或构造函数参数来解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

我认为你不需要所有的重复和额外的注释属性。如果名称与object属性相同,则默认使用它。

所以您可以将其声明为:

@Root
class Address {
    @Attribute
    private final String street;

    @Attribute
    private final String city;

    @Attribute
    private final String state;

    public Address(String street, String city, String state) {
        super();
        this.street = street;
        this.city = city;
       this.state = state;
   }

   @Override
   public String toString() {
      return "Address [city=" + city + ", state=" + state + ", street=" + street + "]";
   }   
}

答案 1 :(得分:0)

如果Java实现Serializable并遵守JavaBean语法,Java将默认序列化所有类成员。

答案 2 :(得分:0)

我有类似的担忧,但有相当复杂的对象结构。 我通过使用JAXB库进行编组和解编来解决这个问题,这是一个非常常见的问题。 您还可以考虑通过使用方面将编组逻辑与java类完全分离 - 您可以在单独的方面处理所有注释,这将使您的java类完全清除编组注释。