使用 GSON 和 Hibernate 实体创建自定义 JSON

Create Custom JSON using GSON and Hibernate Entity

我有以下 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 return JSON 形式的实体:

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

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

以及以下 returned JSON:

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

在上面的JSON中,它return编了一个成本数组,但我需要的是return只有第一个'cost',像这样:

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

如何实现?

谢谢!

我有以下建议:

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

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();