免责声明:我对这一切都不熟悉,所以我的术语可能是错误的
我有一些Java POJO我要序列化为JSON& XML。我正在使用MOXy 2.5.0 for JSON和Jersey 2.4.1。
@XmlRootElement
class Root {
// @XmlElements({@XmlElement(name = "destination_address", type = LatLong.class),
// @XmlElement(name = "destination_address", type = Polygon.class)})
public Object[] destination_addresses;
}
public class LatLong {
public double lat, lng;
}
public class Polygon {
protected List<LatLong> points = new ArrayList<LatLong>();
@XmlElements({@XmlElement(name = "lat", type = Lat.class),
@XmlElement(name = "lng", type = Lng.class)})
private LatOrLong[] getLatOrLongs() {
LatOrLong[] retval = new LatOrLong[points.size() * 2];
for (int point = 0; point < points.size(); point++) {
LatLong latLong = points.get(point);
retval[point * 2] = new Lat(latLong.lat);
retval[point * 2 + 1] = new Lng(latLong.lng);
}
return retval;
}
static abstract private class LatOrLong {
@XmlValue
private double latOrLong;
private LatOrLong() {}
private LatOrLong(double latOrLong) {this.latOrLong = latOrLong;}
}
static private class Lat extends LatOrLong {
private Lat() {}
private Lat(double lat) {super(lat);}
}
static private class Lng extends LatOrLong {
private Lng() {}
private Lng(double lng) {super(lng);}
}
}
这在注释掉两行的XML中不起作用,但在JSON中,MOXy正在向type: latLong
数组添加destination_addresses
属性,以及使用toString()
Polygon
的方法。
type
?getLatOrLongs()
代替toString()
? 编辑:我已将Polygon
简化为序列化points
并将destination_addresses
更改为List<Object>
而非Object[]
}。
答案 0 :(得分:0)
默认情况下,使用MOXy启用pojo映射功能。
但是,无论如何,你需要实现一个特定的marshal / unmarshal(我从MongoDB这里拿到ObjectID,这是一个t:
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.bson.types.ObjectId;
public class ObjectIdXmlAdapter extends XmlAdapter<String, ObjectId> {
@Override
public String marshal(ObjectId id) throws Exception {
if(id == null) {
return null;
} else {
return id.toString();
}
}
@Override
public ObjectId unmarshal(String id) throws Exception {
return new ObjectId(id);
}
}
然后,在你的POJO上:
@XmlJavaTypeAdapter(ObjectIdXmlAdapter.class)
public ObjectId getId() {
return id;
}
将按预期序列化您的id元素......
希望这有帮助,这应该是主要的麻烦。