注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB 2 (JSR-222)专家组的成员。
圆圈
对于 MOXy,唯一需要的注释将@XmlElement
在area
属性上,因为没有对应于 getter 的 setter。包含在@XmlElement
Java SE 6 及更高版本中:
package forum10028037;
import javax.xml.bind.annotation.XmlElement;
class Circle{
private float radius;
private float pi;
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
}
public float getPi() {
return pi;
}
public void setPi(float pi) {
this.pi = pi;
}
@XmlElement
public float getArea(){
return pi * radius * radius;
}
}
演示
package forum10028037;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Circle.class);
Circle circle = new Circle();
circle.setPi(3.14f);
circle.setRadius(10.1f);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.setProperty("eclipselink.json.include-root", false);
marshaller.marshal(circle, System.out);
}
}
输出
{
"area" : 320.31143,
"pi" : 3.14,
"radius" : 10.1
}
了解更多信息