簡體   English   中英

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

[英]How to exclude fields during serialization of gson

我有兩個實體: OneToMany關系中的OrderItem 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;
}

我使用gson序列化Orders並將它們發送到另一台機器,但由於訂單和項目相互引用,在序列化過程中創建了一個循環。

我的目標是,當加載一個Item時,字段id_order應該為null或僅包含 id,以避免傳播。 休眠是否支持此功能? 或者我可以在序列化期間排除該字段嗎?

我已經在Item上嘗試過FetchType.LAZY並在onLoad() Interceptor捕獲Item並將其id_order設置為null 但它沒有用。 我試圖避免編寫自定義適配器或在每次查詢時手動解析所有訂單中的所有項目。

我相信它與Hibernate相比並不多,但GSON更多。 您應該定義序列化/反序列化規則。

最簡單的方法是使用@Expose注釋,從序列化/反序列化中包含/排除給定屬性:

@Expose(serialize = false, deserialize = false)

另一種方法是為givem類定義自定義適配器。 使用適配器,您可以完全覆蓋GSON序列化或反序列化對象的方式。

例如:

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
    }
}

最后初始化你的Gson解析器的實例:

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

如果要避免寫入整個序列化,可以使用@Expose排除字段,然后在其中編寫帶有純GSON實例的適配器,使用該純實例進行序列化/反序列化並手動添加該字段。

處理序列化/反序列化問題的另一種方法是使用此處描述的ExclusionStrategyhttps//google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/ExclusionStrategy.html

我知道這並不能直接回答問題,但可能會幫助其他人,GSON 可以選擇基於變量修飾符進行排除。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM