项目有两个实体:
@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的Cutomer实体转换为
{
"id":1,
"city":{"id":1, "name":"New York"}
}
我希望它转换为
{
"id":1,
"city_id":1
}
我怎么能通过gson或jackson做到这一点?
答案 0 :(得分:0)
这个问题可能对您有所帮助。
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;
...
}