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

VHanded

我有以下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"
           },
}

如何做到这一点?

谢谢!

桑耶夫·萨哈(Sanjeev Saha)

我有以下建议:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章