1

Parceler's readme states that it can be used with other POJO based libraries, in particular SimpleXML.

Are there any examples available demonstrating the usage?

I've used Parceler with GSON successfully:

Gson gson = new GsonBuilder().create();
ParcelerObj parcelerObj = gson.fromJson(jsonStr, ParcelerObj.class);
String str = gson.toJson(parcelerObj);

However, I'm not sure where to start with SimpleXML. I currently have the following SimpleXML class:

@Root(name="point")
@Order(attributes={"lat", "lon", " alt"})
public class SensorLocation {
    @Attribute
    private double lat;

    @Attribute
    private double lon;

    @Attribute
    private double alt;

    public SensorLocation (
        @Attribute(name="lat") double lat,
        @Attribute(name="lon") double lon,
         @Attribute(name="alt") double alt
    ) {
        this.lat = lat;
        this.lon = lon;
        this.alt = alt;
    }
}

This class can then be serialized into the following XML

<point lat="10.1235" lon="-36.1346" alt="10.124"/>

Using the following code:

SensorLocation sl = new SensorLocation (10.1235, -36.1346, 10.124);
Serializer s = new Persister();
ByteArrayOutputStream out = new ByteArrayOutputStream();
s.write(sl, out);

I currently have a strange requirement to keep XML attributes and elements in particular order. That's why I'm using @Order.

How would Parceler work with SimpleXML? Would I pass Parceler instance into Serializer.write()?

If anyone can point me to a resource, I can do my own research. I just couldn't find any starting point.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
Vadym
  • 964
  • 1
  • 13
  • 31

1 Answers1

1

Here's an example of your bean that supports both SimpleXML and Parceler:

@Parcel
@Root(name="point")
@Order(attributes={"lat", "lon", " alt"})
public class SensorLocation {
    @Attribute
    private double lat;

    @Attribute
    private double lon;

    @Attribute
    private double alt;

    @ParcelConstructor
    public SensorLocation (
        @Attribute(name="lat") double lat,
        @Attribute(name="lon") double lon,
        @Attribute(name="alt") double alt
    ) {
        this.lat = lat;
        this.lon = lon;
        this.alt = alt;
    }
}

Worth noting, this configuration of Parceler will use reflection to access your bean's fields. Using non-private fields will avoid a warning and a slight performance hit.

Usage:

SensorLocation sl = new SensorLocation (10.1235, -36.1346, 10.124);
Parcelable outgoingParcelable = Parceler.wrap(sl);
//Add to intent, etc.

//Read back in from incoming intent
Parcelable incomingParcelable = ...
SensorLocation sl = Parceler.unwrap(incomingParcelable);
Serializer s = new Persister();
ByteArrayOutputStream out = new ByteArrayOutputStream();
s.write(sl, out);

Because Parceler doesn't introduce any code into your bean you're free to do with it what you want.

John Ericksen
  • 10,995
  • 4
  • 45
  • 75