java - 将 hibernate 实体转换为 JSON : oblectId instead of whole object

标签 java json hibernate

项目有两个实体:

@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/

相关文章:

java - 编写 Jena 内置函数

java - RSA 算法实现在 Java 中无法正常工作

asp.net-mvc - 自定义模型绑定(bind)器不验证模型

hibernate - 为什么我的 grails JMS 消息处理服务使用陈旧数据?

java - Hibernate - EhCache - 缓存关联/集/集合的哪个区域?

java - 为什么我的 HttpClient 类卡住某些 URL

java - Google App Engine 中的 e.printStackTrace

php - 编写自定义查询来获取 WordPress 数据/使用 WordPress 表创建 JSON

json - 将结构转换为 Json 的最佳方法是什么?

spring-boot:如果密码失败,则在没有数据库的情况下启动应用程序