Java POJO作为JSON编组所需的最小结构是什么?

时间:2012-04-05 11:50:49

标签: java json marshalling

这很直截了当。将Java POJO作为JSON编组的最低要求结构是什么?

如果对象只有getter / setter,或者字段声明是强制性的,那么你可以将对象编组为JSON吗?

Setter / Getter示例:

class Circle{
 private float radius;
 private float pi;

 // setter and getters for those aboce;

 public float getArea(){
 // returns the computed area;
 }
}

如果“area”字段未在Foo类中定义为字段,那么这样的对象是否可以作为JSON编组?或者是否必须明确声明POJO中的所有字段?

3 个答案:

答案 0 :(得分:1)

这实际上取决于编组引擎。最近在Spring下使用jackson-mapper,如果我没有getter操作(getArea()很好的例子)那么我的实例就无法正确编组。

假设,如果你有标准的bean set / get(或者在你的情况下获得),它应该没问题。

答案 1 :(得分:1)

如果使用Google Gson库,则不需要getter / setter:

user guide的示例:

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);  
==> json is {"value1":1,"value2":"abc"}

答案 2 :(得分:1)

注意:我是EclipseLink JAXB (MOXy)主管,是JAXB 2 (JSR-222)专家组的成员。

<强>环

对于MOXy,@XmlElement属性上唯一需要的注释是area,因为没有与getter对应的setter。 {SE} 6及更高版本中包含@XmlElement

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
}

了解更多信息