项目有两个实体:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "city_id", nullable = true)
private City city;
...
}
和
@Entity
public class City {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "name", nullable = false)
private String name;
...
}
使用 Gson 或 Jackson 转换为 JSON 的客户实体
{
"id":1,
"city":{"id":1, "name":"New York"}
}
我希望它转换为
{
"id":1,
"city_id":1
}
我如何通过 gson 或 jackson 做到这一点?
最佳答案
这个问题可能对你有帮助。
Gson: How to exclude specific fields from Serialization without annotations
我不知道是否有直接的方法来实现这一点,但有一些间接的方法可以做到这一点。例如,您可以将 private City city
标记为 transient
,然后您可以公开另一个名为 city_id
的字段,该字段只是城市 ID。它看起来像这样:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "city_id", nullable = true)
private transient City city;
private int city_id;
...
}
关于java - 将 hibernate 实体转换为 JSON : oblectId instead of whole object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375654/