简单的XML反序列化 [英] Simple XML deserialization

查看:127
本文介绍了简单的XML反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying out the Simple XML serializer. I am more interested in deserialization from XML->Java. Here is my code as a unit test:

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 + "]";
    }   
}

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

This works, but the repeated @Attribute annotations (at the field and at the constructor argument) in the Address class look ugly. Is there some way to:


  • 从字段名称中简单地找出属性名称?

  • 有简单的忽略序列化,以便我可以撇开字段或构造函数参数?

推荐答案

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

I don't think you need all that repetition and the extra annotations' attribute. If the name is the same as the object attribute, it will be used by default.

所以您可以将其声明为:

so you can just declare it as:

@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 + "]";
   }   
}

这篇关于简单的XML反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆