Gson忽略字段@Export注解使用,以及动态忽略字段使用

本文介绍如何使用@Expose注解控制Gson序列化和反序列化过程中的字段暴露,并提供一种动态忽略特定字段的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:@Expose 默认有两个属性:serialize 和 deserialize,默认值都为 true,如果你给字段设置了 @Expose 注解,但是没有设置serialize 和 deserialize,那 model 的字段都将会输出。
public class UserSimple { 
        @Expose()
        String name; // equals serialize & deserialize

        @Expose(serialize = false, deserialize = false)
        String email; // equals neither serialize nor deserialize

        @Expose(serialize = false)
        int age; // equals only deserialize

        @Expose(deserialize = false)
        boolean isDeveloper; // equals only serialize
}

根据 @Expose 的用法,UserSimple 序列化 JSON 输出只有 name 和 isDeveloper,其他连个字段就不会被输出,因为 serialize 都是 false;

反序列化的话,只有 email 和 isDeveloper 被忽略,因为 deserialize = false

使用 @Expose 的前期是我们也需要使用 GsonBuilder 创建一个 Gson 实例:

GsonBuilder builder = new GsonBuilder();  
builder.excludeFieldsWithoutExposeAnnotation();  
Gson gson = builder.create();  
  • 1
  • 2
  • 3
  • 4

只有这样 Gson 在解析的时候 @Expose 才会生效。

二:这种情况是动态忽略字段

我遇到的情况是:字段继承DataSupport,使用Gson的toJson方法时,会多出父类的几个字段,所以需要动态的设置就可以忽略这几个字段了,如下:
public static Gson skipBaseId(){
  Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
   
   @Override
   public boolean shouldSkipField(FieldAttributes f) {
    // TODO Auto-generated method stub
    return f.getName().equals("baseObjId")|f.getName().equals("associatedModelsMapForJoinTable")|f.getName().equals("associatedModelsMapWithFK")
      |f.getName().equals("associatedModelsMapWithoutFK")
      |f.getName().equals("listToClearAssociatedFK")|f.getName().equals("listToClearSelfFK");
   }
   
   @Override
   public boolean shouldSkipClass(Class<?> clazz) {
    // TODO Auto-generated method stub
    return false;
   }
  }).create();
  return gson;
 }

shouldSkipField方法中使忽略字段,shouldSkipClass是忽略类。

package com.example.kucun2.DataPreserver; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.example.kucun2.entity.*; import com.example.kucun2.entity.data.SynchronizableEntity; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class DataExporter { private final DataStore dataStore; // 将 ExportData 改为静态内部类 public static class ExportData { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_bancai> dingdan_bancais; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } public DataExporter(DataStore dataStore) { this.dataStore = dataStore; } public String exportToJson() { ExportData exportData = new ExportData(); exportData.bancais = new ArrayList<>(dataStore.bancais.getViewList()); exportData.caizhis = new ArrayList<>(dataStore.caizhis.getViewList()); exportData.mupis = new ArrayList<>(dataStore.mupis.getViewList()); exportData.chanpins = new ArrayList<>(dataStore.chanpins.getViewList()); exportData.chanpin_zujians = new ArrayList<>(dataStore.chanpin_zujians.getViewList()); exportData.dingdans = new ArrayList<>(dataStore.dingdans.getViewList()); exportData.dingdan_chanpins = new ArrayList<>(dataStore.dingdan_chanpins.getViewList()); exportData.dingdan_bancais = new ArrayList<>(dataStore.dingdan_bancais.getViewList()); exportData.kucuns = new ArrayList<>(dataStore.kucuns.getViewList()); exportData.zujians = new ArrayList<>(dataStore.zujians.getViewList()); exportData.users = new ArrayList<>(dataStore.users.getViewList()); exportData.jinhuos = new ArrayList<>(dataStore.jinhuos.getViewList()); Gson gson = new GsonBuilder() .registerTypeAdapter(SynchronizableEntity.class, new SmartEntitySerializer()) .setPrettyPrinting() .create(); return gson.toJson(exportData); } public void importFromJson(String json, Context context) { // 使用 TypeToken 正确获取 ExportData 类型 Type exportDataType = new TypeToken<ExportData>(){}.getType(); Gson gson = new GsonBuilder() .registerTypeAdapter(SynchronizableEntity.class, new SmartEntityDeserializer()) .create(); ExportData importData = gson.fromJson(json, exportDataType); clearDataStorePreservingDefaults(); addAllToDataStore(importData); saveToPreferences(context, json); } private void clearDataStorePreservingDefaults() { preserveDefaults(dataStore.bancais); preserveDefaults(dataStore.caizhis); preserveDefaults(dataStore.mupis); preserveDefaults(dataStore.chanpins); preserveDefaults(dataStore.chanpin_zujians); preserveDefaults(dataStore.dingdans); preserveDefaults(dataStore.dingdan_chanpins); preserveDefaults(dataStore.dingdan_bancais); preserveDefaults(dataStore.kucuns); preserveDefaults(dataStore.zujians); preserveDefaults(dataStore.users); preserveDefaults(dataStore.jinhuos); } private <T extends SynchronizableEntity> void preserveDefaults(SynchronizedList<T> list) { List<T> preserved = new ArrayList<>(); for (T entity : list.getViewList()) { if (entity.getId() == -1) { preserved.add(entity); } } list.getViewList().clear(); list.getViewList().addAll(preserved); } private void addAllToDataStore(ExportData data) { if (data.bancais != null) dataStore.bancais.getViewList().addAll(data.bancais); if (data.caizhis != null) dataStore.caizhis.getViewList().addAll(data.caizhis); if (data.mupis != null) dataStore.mupis.getViewList().addAll(data.mupis); if (data.chanpins != null) dataStore.chanpins.getViewList().addAll(data.chanpins); if (data.chanpin_zujians != null) dataStore.chanpin_zujians.getViewList().addAll(data.chanpin_zujians); if (data.dingdans != null) dataStore.dingdans.getViewList().addAll(data.dingdans); if (data.dingdan_chanpins != null) dataStore.dingdan_chanpins.getViewList().addAll(data.dingdan_chanpins); if (data.dingdan_bancais != null) dataStore.dingdan_bancais.getViewList().addAll(data.dingdan_bancais); if (data.kucuns != null) dataStore.kucuns.getViewList().addAll(data.kucuns); if (data.zujians != null) dataStore.zujians.getViewList().addAll(data.zujians); if (data.users != null) dataStore.users.getViewList().addAll(data.users); if (data.jinhuos != null) dataStore.jinhuos.getViewList().addAll(data.jinhuos); } public void saveToPreferences(Context context, String json) { SharedPreferences prefs = context.getSharedPreferences("DataStore", Context.MODE_PRIVATE); prefs.edit().putString("jsonData", json).apply(); } public void loadFromPreferences(Context context) { SharedPreferences prefs = context.getSharedPreferences("DataStore", Context.MODE_PRIVATE); String json = prefs.getString("jsonData", null); if (json != null) { importFromJson(json, context); } } private static class SmartEntitySerializer implements JsonSerializer<SynchronizableEntity> { @Override public JsonElement serialize(SynchronizableEntity src, Type type, JsonSerializationContext context) { JsonObject json = new JsonObject(); json.addProperty("id", src.getId()); json.addProperty("className", src.getClass().getName()); // 其他字段序列化... return json; } } private static class SmartEntityDeserializer implements JsonDeserializer<SynchronizableEntity> { @Override public SynchronizableEntity deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); String className = obj.get("className").getAsString(); try { Class<?> clazz = Class.forName(className); SynchronizableEntity entity = (SynchronizableEntity) clazz.newInstance(); entity.setId(obj.get("id").getAsInt()); // 其他字段反序列化... return entity; } catch (Exception e) { throw new JsonParseException(e); } } } } 详细注解
最新发布
06-26
// 文件路径: kucun2/entity/data/DataExporter.java package com.example.kucun2.entity.data; import android.content.Context; import android.content.SharedPreferences; import com.example.kucun2.entity.SynchronizableEntity; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; /** * 数据导入导出器 - 负责数据的持久化和恢复 */ public class DataExporter { private final DataStore dataStore; public DataExporter(DataStore dataStore) { this.dataStore = dataStore; } public String exportToJson() { ExportData exportData = new ExportData(); exportData.bancais = new ArrayList<>(dataStore.bancais); exportData.caizhis = new ArrayList<>(dataStore.caizhis); // 初始化其他列表... Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(SynchronizableEntity.class, new EntitySerializer()) .create(); return gson.toJson(exportData); } public void importFromJson(String json, Context context) { Gson gson = new GsonBuilder() .registerTypeAdapter(SynchronizableEntity.class, new EntityDeserializer()) .create(); Type exportType = new TypeToken<ExportData>(){}.getType(); ExportData importData = gson.fromJson(json, exportType); // 更新数据列表 updateList(dataStore.bancais, importData.bancais); updateList(dataStore.caizhis, importData.caizhis); // 更新其他列表... // 重新建立关联 DataAssociator associator = new DataAssociator(dataStore); associator.automaticAssociation(); setAllEntitiesState(SynchronizableEntity.SyncState.MODIFIED); saveToPreferences(context, json); } private void saveToPreferences(Context context, String json) { SharedPreferences prefs = context.getSharedPreferences("DataStore", Context.MODE_PRIVATE); prefs.edit().putString("jsonData", json).apply(); } public void loadFromPreferences(Context context) { SharedPreferences prefs = context.getSharedPreferences("DataStore", Context.MODE_PRIVATE); String json = prefs.getString("jsonData", null); if (json != null) { importFromJson(json, context); } } private static class EntityDeserializer implements JsonDeserializer<SynchronizableEntity> { @Override public SynchronizableEntity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { JsonObject obj = json.getAsJsonObject(); String entityType = obj.get("entityType").getAsString(); Integer id = obj.get("id").getAsInt(); try { Class<?> clazz = Class.forName("com.example.kucun2.entity." + entityType); SynchronizableEntity entity = (SynchronizableEntity) clazz.newInstance(); entity.setId(id); return entity; } catch (Exception e) { return null; } } } private static class EntitySerializer implements JsonSerializer<SynchronizableEntity> { @Override public JsonElement serialize(SynchronizableEntity src, Type typeOfSrc, JsonSerializationContext context) { JsonObject obj = new JsonObject(); obj.addProperty("id", src.getId()); obj.addProperty("entityType", src.getClass().getSimpleName()); return obj; } } public static class ExportData { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_chanpin_zujian> dingdan_chanpin_zujians; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } }
06-18
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_zxw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值