Simple XML deserialization

I tried Simple XML serializer . I'm more interested in deserialization from XML-> Java. Here is my code as 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 + "]";
    }   
}

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

  • just determine the attribute name from the field name?
  • have a simple serialization of ignoring, so that I can get away with annotating fields or constructor argument?
+5
source share
3 answers

, . , .

:

@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

Java , Serializable JavaBean.

0

, . , JAXB -, . java - , java .

0

All Articles