java - 使用 GSON 和 Hibernate Entity 创建自定义 JSON

标签 java json hibernate jax-rs gson

我有以下 Hibernate 实体:

@Entity
public class DesignActivity implements Serializable {

    @Id
    @Expose
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;


    @Version
    @Column(name = "version")
    private int version;

    @Expose
    @NotEmpty
    @NotNull
    private String name;


    @NotNull
    @OneToMany (mappedBy = "designActivity", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
    private Set<Cost> costs = new HashSet<Cost>();

// getter and setter
}

还有以下 GSON 代码,用于通过 JAX-RS 返回 JSON 形式的实体:

BaseDesign baseDesign = em.find(BaseDesign.class, id);

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
return Response.ok(gson.toJson(baseDesign)).build();

返回的 JSON 如下:

{
    "id":1,
    "name":"Sew Collar",
    "costs":[
        {
             "value":"1.05"
        },
        {
             "value":"1.2"
        }
    ]
}

在上面的 JSON 中,它返回了一个成本数组,但我需要的是仅返回第一个“成本”,如下所示:

{
    "id":1,
    "name":"Sew Collar",
    "cost":{
             "value":"1.05"
           },
}

如何实现这一目标?

谢谢!

最佳答案

我有以下建议:

1) 请创建以下自定义 JsonSerializer 以排除 成本 并包含 成本:

import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class CustomSerializer implements JsonSerializer<BaseDesign> {
@Override
public JsonElement serialize(BaseDesign src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject object = new JsonObject();
    object.addProperty("id", src.getId());
    object.addProperty("name", src.getName());
    List<Cost> listOfCost = src.getCosts();
    if (listOfCost != null && listOfCost.size() != 0) {
        object.addProperty("cost", listOfCost.get(0).getValue());
        object.remove("costs");
    }
    return object;
  }

}

2) 按以下方式创建 gson 对象:

Gson gson = new GsonBuilder() .registerTypeAdapter(BaseDesign.class, new CustomSerializer()) .excludeFieldsWithoutExposeAnnotation() .create();

关于java - 使用 GSON 和 Hibernate Entity 创建自定义 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37627699/

相关文章:

java - JAXB 解码时出错

Java:简单的数组分割程序

javascript - json数据显示在表格中

json - Circe Decoder - 如果失败则回退到另一个解码器

java - Hibernate Annotation 中的多重模式匹配

java - JPA Hibernate 映射超过 2 个实体

java子类问题

java - 加载资源文件时出现问题

c# - 有没有办法让 JSON.net 尊重 System.Text.Json JsonPropertyName 属性

hibernate - 强制 Hibernate 使用 ON DELETE CASCADE 创建外键