MOXy添加类型并使用toString?

时间:2013-12-05 08:54:31

标签: java json jaxb jersey moxy

免责声明:我对这一切都不熟悉,所以我的术语可能是错误的

我有一些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的方法。

  1. 如何隐藏type
  2. 如何让MOXy使用getLatOrLongs()代替toString()
  3. 编辑:我已将Polygon简化为序列化points并将destination_addresses更改为List<Object>而非Object[] }。

1 个答案:

答案 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元素......

希望这有帮助,这应该是主要的麻烦。