简体   繁体   English

如何在gson序列化期间排除字段

[英]How to exclude fields during serialization of gson

I have two entities: Order and Item in a OneToMany relationship.我有两个实体: OneToMany关系中的OrderItem Item belongs an Order, and the Order has a set of Items. Item 属于一个 Order,而 Order 有一组 Items。

class Order{
     @OneToMany(fetch = FetchType.EAGER, mappedBy = "id_order")
     Set<Item> items;
}

class Item{
     @ManyToOne(targetEntity = Order.class, fetch = FetchType.LAZY)
     @JoinColumn(name = "id_order")
     Order id_order;
}

I use gson to serialize Orders and send them to another machine, but a loop is being created during serialization, due to both orders and items having a reference to each other.我使用gson序列化Orders并将它们发送到另一台机器,但由于订单和项目相互引用,在序列化过程中创建了一个循环。

My goal is that when an Item is loaded, the field id_order should either be null or contain only the id, to avoid propagation.我的目标是,当加载一个Item时,字段id_order应该为null或仅包含 id,以避免传播。 Does hibernate support this feature?休眠是否支持此功能? Or can I exclude the field during serialization?或者我可以在序列化期间排除该字段吗?

I already tried FetchType.LAZY on Item and catching Item inside an onLoad() Interceptor and setting its id_order to null .我已经在Item上尝试过FetchType.LAZY并在onLoad() Interceptor捕获Item并将其id_order设置为null But it didn't work.但它没有用。 I am trying to avoid writing a custom adapter or manually parsing all Items inside all Orders at every query.我试图避免编写自定义适配器或在每次查询时手动解析所有订单中的所有项目。

I believe it has not much with Hibernate, but more with GSON. 我相信它与Hibernate相比并不多,但GSON更多。 You should define serialization/deserialization rule. 您应该定义序列化/反序列化规则。

Easiest way is to use @Expose annotation, to include/exclude given property from serialization/deserialization: 最简单的方法是使用@Expose注释,从序列化/反序列化中包含/排除给定属性:

@Expose(serialize = false, deserialize = false)

Another way is to define custom adapters for givem class. 另一种方法是为givem类定义自定义适配器。 WIth Adapter you can completely override the way GSON serialize or deserialize object. 使用适配器,您可以完全覆盖GSON序列化或反序列化对象的方式。

For example: 例如:

public class YourAdapter implements JsonDeserializer<Order>, JsonSerializer<Order> {
    @Override
    public Orderde serialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    // your logic
    }

    @Override
    public JsonElement serialize(Ordersrc, Type typeOfSrc, JsonSerializationContext context) {
        // your logic
    }
}

Finally initialize instance of your Gson parser: 最后初始化你的Gson解析器的实例:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Order.class, new YourAdapter())
        .build();

If you want to avoid writting whole serialization, you could exclude your field by using @Expose , and then write adapter with pure instance of GSON in it, serialize/deserialize using that pure one and manually add that one field. 如果要避免写入整个序列化,可以使用@Expose排除字段,然后在其中编写带有纯GSON实例的适配器,使用该纯实例进行序列化/反序列化并手动添加该字段。

Another way of dealing with serialization/deserialization problem is to use ExclusionStrategy described here: https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/ExclusionStrategy.html 处理序列化/反序列化问题的另一种方法是使用此处描述的ExclusionStrategyhttps//google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/ExclusionStrategy.html

I know this doesnt answer the question derectly but might help others, GSON has an option to exclude based on a vairiables modifier.我知道这并不能直接回答问题,但可能会帮助其他人,GSON 可以选择基于变量修饰符进行排除。

Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PRIVATE).create(); Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PRIVATE).create();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM