Java Gson在序列化期间排除字段

时间:2016-12-01 11:13:27

标签: java serialization gson

我有一个ConfigInstance类,其中包含passwordpassword_hash。 现在我想使用gson序列化对象,但不包括password字段。

public class ConfigInstance {
    public String database_address;
    public int database_port;
    public String database_user;

    @Expose(serialize = false)
    private String database_pass;
    public String database_pass_hash;

    public String GetPass() { return database_pass; }

    public void Encrypt() { /* Creates the hash before serializing*/ }

    public void Decrypt() { /* Creates the password after deserializing */}
}

正如您所看到的,我尝试过使用@Expose(serialize = false)但它似乎没有做任何事情。此外,我已经将该字段设置为私有,因为我认为这将"覆盖" @Expose

但运行以下代码:

private void toFile(File file, ConfigInstance map) {
    map.Encrypt();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String jsonConfig = gson.toJson(map);
    FileWriter writer;
    try {
        writer = new FileWriter(file);
        writer.write(jsonConfig);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        System.out.println("Error exporting config: " + e.toString());
    }
}

仍会导致以下文件内容没有错误:

{
  "database_address": "127.0.0.1",
  "database_port": 1521,
  "database_user": "test",
  "database_pass": "test1234",
  "database_pass_hash": "B9FE2C011B59F0D0D383D70073E48A19"
}

那么我做错了什么?我现在非常无能为力,感谢任何帮助,因为THIS似乎无法发挥作用。

提前致谢。

7 个答案:

答案 0 :(得分:27)

要获得此结果,您需要使用@Expose注释所有字段:

public class ConfigInstance {

    @Expose
    public String database_address;
    @Expose
    public int database_port;
    @Expose
    public String database_user;

    @Expose(serialize = false)
    private String database_pass;
    @Expose
    public String database_pass_hash;

并将Gson配置为仅显示已注释的字段并忽略其余字段,如下所示:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

然后,你会得到:

{
  "database_address": "127.0.0.1",
  "database_port": 1521,
  "database_user": "test",
  "database_pass_hash": "B9FE2C011B59F0D0D383D70073E48A19"
}

此外,在对字符串进行反序列化时,您还将拥有密码属性。

但是,您仍然可以配置Gson Serializer来完成此任务。

答案 1 :(得分:21)

这是另一种方式。

序列:

Gson gson = new GsonBuilder()
            .addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getName().toLowerCase().contains("fieldName");
                }

                @Override
                public boolean shouldSkipClass(Class<?> aClass) {
                    return false;
                }
            })
            .create();

反序列化:

Gson gson = new GsonBuilder()
            .addDeserializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getName().toLowerCase().contains("fieldName");
                }

                @Override
                public boolean shouldSkipClass(Class<?> aClass) {
                    return false;
                }
            })
            .create();

答案 2 :(得分:16)

如果您希望特定字段不被序列化,请为其提供一个临时关键字

private transient String database_pass;

访问https://sites.google.com/site/gson/gson-user-guide#TOC-Finer-Points-with-Objects了解更多信息

答案 3 :(得分:11)

@utkusonmez 尽管提到的方法是错误的,但这个答案仍然有效。 它应该使用'addSerializationExclusionStrategy'而不是'addDeserializationExclusionStrategy'

所以答案看起来像是

Gson gson = new GsonBuilder()
            .addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getName().toLowerCase().contains("fieldName");
                }

                @Override
                public boolean shouldSkipClass(Class<?> aClass) {
                    return false;
                }
            })
            .create();

gson.toJson(*OBJ_TO_SERIALIZE*))

答案 4 :(得分:4)

如果您只想禁用序列化或仅禁用反序列化,则可以使用@Expose注释属性,例如:

@Expose(serialize = false, deserialize = true)

默认选项为true,因此此处不需要反序列化。

答案 5 :(得分:1)

这是一个迟到的答案,但它可能对某人有帮助。

您只需执行@Expose(serialize = false, deserialize = false)或只需要您想要的内容。

如果您有serializedeserialize true,则根本不需要@Expose

创建此类:

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.annotations.Expose;

public class NoModuleExclusionStrategy implements ExclusionStrategy {

    private final boolean deserialize;

    public NoModuleExclusionStrategy(boolean isdeserialize) {
        deserialize = isdeserialize;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }

    @Override
    public boolean shouldSkipField(FieldAttributes field) {
        return !(field.getAnnotation(Expose.class) == null || (deserialize ? field.getAnnotation(Expose.class).deserialize() : field.getAnnotation(Expose.class).serialize()));
    }

}

然后用GsonBuilder构建Gson

Gson gson = new GsonBuilder()
.addSerializationExclusionStrategy(new NoModuleExclusionStrategy(false))
.addDeserializationExclusionStrategy(new NoModuleExclusionStrategy(true))
.create();

您的ConfigInstance类如下所示

{
  "database_address": "127.0.0.1",
  "database_port": 1521,
  "database_user": "test",
  "database_pass_hash": "B9FE2C011B59F0D0D383D70073E48A19"
}

答案 6 :(得分:0)

这是一个非常简单的解决方案,只需一行代码,没有任何@Expose注释或排除策略。

Gson中实现的默认行为是null object fields are ignored。因此,您所需要做的就是在序列化之前将密码字段设置为null。

map.setPassword(null); // or map.password = null;
String jsonConfig = gson.toJson(map); // This won't serialize null password field
相关问题