Parceler的自述文件声明它可以与其他基于POJO的库,特别是SimpleXML一起使用。
是否有可用的例子来说明使用情况?
我在GSON中成功地使用了Parceler:
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()中吗?
如果有人能给我指点资源,我可以自己做研究。我只是找不到任何起点。
发布于 2016-04-24 06:05:53
下面是一个支持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中引入任何代码,所以您可以随意使用它。
https://stackoverflow.com/questions/36807463
复制相似问题