gpt4 book ai didi

json - @JsonRootName 不起作用

转载 作者:行者123 更新时间:2023-12-02 00:27:12 24 4
gpt4 key购买 nike

我有这个简单的 Java 实体,我需要将其设为 Json 输出,我可以通过网络服务实现该输出。

@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

关于json - @JsonRootName 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36107564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com