gpt4 book ai didi

java - 使用 Spring Boot、fasterxml jackson 和 @OneToMany 注释将集合添加到 JSON 响应

转载 作者:行者123 更新时间:2023-12-02 04:32:58 31 4
gpt4 key购买 nike

我正在使用带有fasterxml jackson注释的spring boot v1.2.3,并且我试图将整个同级集合公开到单个JSON响应中,但似乎不能仅仅使用正确的方法将添加的集合添加到响应中注释和神秘代码。

有人可以帮我解决这个问题吗?

我不确定这是否是 Spring Boot 中的原因,或者只是注释之间的配置不正确。我希望将集合添加到子数据库中的 json 中。

@Entity
@Table(name = "station")
public class Station implements Serializable {



@OneToMany(mappedBy = "station", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private Set<StationTank> stationTanks;

@JsonManagedReference("station-tank")
public Set<StationTank> getStationTanks() {

System.out.println("get tank count: " + stationTanks.size());
return stationTanks;
}

public void setStationTanks(Set<StationTank> stationTanks) {

System.out.println("set tank count: " + stationTanks.size());

this.stationTanks = stationTanks;
}


}



@Entity
@Table(name = "station_tank")
public class StationTank implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "station_tank_id")
private long stationTankId;


@Column(name = "active",nullable=true, columnDefinition="Boolean default false")
private Boolean active;


@ManyToOne(cascade = CascadeType.ALL, optional = false) // as defined in schema
@JoinColumn(name = "station_id")
private Station station;


@JsonBackReference("station-tank")
public Station getStation() {
return station;
}

public void setStation(Station station) {
this.station = station;
}

}

调用此 URL 我没有将同级集合添加到响应中,但我希望在响应中添加同级集合。 http://localhost:8080/stations/1

{
"stationId": 1,
"stationName": "station name 1",
"active": true,
"_links":
{
"self":
{
"href": "http://localhost:8080/stations/1"
},
"stationTanks":
{
"href": "http://localhost:8080/stations/1/stationTanks"
}
}
}

但是当我调用同级集合的 URL 时,我得到了同级集合,只是我想要上面的响应中的同级集合。

{
"_embedded":
{
"station_tanks":
[
{
"stationTankId": 1,
"active": true,
"_links":
{
"self":
{
"href": "http://localhost:8080/station_tanks/1"
},
"station":
{
"href": "http://localhost:8080/station_tanks/1/station"
}
}
},
{
"stationTankId": 2,
"active": true,
"_links":
{
"self":
{
"href": "http://localhost:8080/station_tanks/2"
},
"station":
{
"href": "http://localhost:8080/station_tanks/2/station"
}
}
}
]
}
}

最佳答案

您可以使用 @JsonView(class) 注释您的字段或 getter并且在 Controller 方法上使用相同的类的相同注释之后 - 这是更好的解决方案,或者只是使用 @JsonIgnore 注释不需要的字段

Here有关 Jackson 配置的更多信息

关于java - 使用 Spring Boot、fasterxml jackson 和 @OneToMany 注释将集合添加到 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31209858/

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