我有这个简单的Java实体,我需要将它作为JSon输出,我可以通过e 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":
[
{
},
{
}
]
}
答案 0 :(得分:3)
如果您想使用@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