2016-04-23 60 views
1

Parceler的自述文件指出,它可以與其他基於POJO的庫一起使用,特別是SimpleXML。Parceler和SimpleXml如Parceler的自述文件中所述

是否有任何示例可用於演示使用情況?

我用Parceler與GSON成功:

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

但是,我不知道從哪裏開始的SimpleXML。目前,我有以下的SimpleXML類:

@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; 
    } 
} 

這個類可以再被序列化爲下面的XML

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

使用下面的代碼:

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

我現在有一個奇怪的規定以特定的順序保持XML屬性和元素。這就是爲什麼我使用@Order

Parceler如何使用SimpleXML?我會將Parceler實例傳入Serializer.write()嗎?

如果有人能指點我的資源,我可以做我自己的研究。我找不到任何起點。

回答

1

下面是支持的SimpleXML和Parceler你的bean的實例:

@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; 
    } 
} 

值得注意的是,Parceler的這個配置將使用反射來訪問你的bean的領域。使用非專用字段將避免警告並輕微影響性能。

用法:

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); 

因爲Parceler不引入任何代碼到你的bean你可以自由用它做你想要的。

+1

哇,很好,這是它的一個簡單的應用程序! – Vadym