我有这个简单的Java实体,我需要使其成为JSon输出,这是通过Web服务实现的。

@Entity
@JsonRootName(value = "flights")
public class Flight implements Serializable {

@Transient
private static final long serialVersionUID = 1L;

public Flight() {
    super();
}

public Flight(FlightDestination destinationFrom, FlightDestination destinationTo, Integer flightPrice, Date date,
        Airplane airplaneDetail) {
    super();
    this.destinationFrom = destinationFrom;
    this.destinationTo = destinationTo;
    this.flightPrice = flightPrice;
    this.date = date;
    this.airplaneDetail = airplaneDetail;
}

public Flight(FlightDestination destinationFrom, FlightDestination destinationTo, Integer flightPrice, Date date) {
    super();
    this.destinationFrom = destinationFrom;
    this.destinationTo = destinationTo;
    this.flightPrice = flightPrice;
    this.date = date;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Enumerated(EnumType.STRING)
private FlightDestination destinationFrom;

@Enumerated(EnumType.STRING)
private FlightDestination destinationTo;

private Integer flightPrice;

@Temporal(TemporalType.DATE)
private Date date;

@OneToOne(cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
@JoinColumn(name = "airplane_fk")
private Airplane airplaneDetail;}


我添加了@JsonRootName,但是我仍然以这种方式获取json输出:

    [
      {

      },

      {

      }
   ]


我还需要向实体添加更多内容,所以最终要获得这种输出:

    {
     "flights":

     [

      {

      },

      {

      }
    ]
   }

最佳答案

如果要使用@JsonRootName(value = "flights"),则必须在ObjectMapper上设置适当的功能

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);


但是,对于List<Flight>这将产生

[
  {"flights": {}},
  {"flights": {}},
  {"flights": {}},
]


因此,您可能必须创建包装器对象:

public class FlightList {
    @JsonProperty(value = "flights")
    private ArrayList<Flight> flights;
}


并且此FlightList将具有{"flights":[{ }, { }]}输出json

10-04 18:31