简体   繁体   English

GSON序列化-如何从序列化中排除某些字段,但不进行反序列化

[英]GSON serialisation - how to exclude some fields from serialisation, but not deserialisation

If I have a type "Person", and it has multiple fields, including "password", then how do I tell GSON that I want accept the password field when it's passed in, but not to pass it back out? 如果我的类型为“ Person”,并且具有多个字段,包括“ password”,那么我如何告诉GSON我希望在传入密码字段时接受密码字段,而不是将其传回?

Specifically, in this case, it's because my web front end can be used to update the password and send it to the Java side,, but I never want to send the password back to the front end (for obvious security reasons). 具体而言,在这种情况下,这是因为我的Web前端可用于更新密码并将其发送到Java端,但是我从不希望将密码发送回前端(出于明显的安全原因)。

I am not sure you can do it with Gson, but you could with Genson . 我不确定您可以使用Gson来做到这一点,但是可以使用Genson来做到 Put @JsonIgnore(deseriaize=true) on your getPassword method. 将@JsonIgnore(deseriaize = true)放在您的getPassword方法上。

Or if you want genson to use only fields instead of public getter/setter and fields, configure it like that: 或者,如果您希望genson仅使用字段而不是公共getter / setter和字段,请按以下方式进行配置:

Genson genson = new Genson.Builder()
      .setUseGettersAndSetters(false)
      .setFieldVisibility(VisibilityFilter.DEFAULT)
      .create();

In that case put the annotation on the field. 在这种情况下,将注释放在字段上。

You can deserialize your class as usual (since you want to deserialize all the fields) and write a custom serializer that excludes the password. 您可以照常反序列化类(因为要反序列化所有字段),并编写一个不包含密码的自定义序列化程序。 Something like this: 像这样:

public class PersonSerializer implements JsonSerializer<Person> {

  @Override
  public JsonElement serialize(Person src, Type typeOfSrc, JsonSerializationContext context)
  {
    JsonObject obj = new JsonObject();
    obj.addProperty("name", src.name);
    obj.addProperty("gender", src.gender);
    obj.addProperty("age", src.age);
    //And all the other fields but the password...

    return obj;
  }
}

Then you just need to register the serializer with: 然后,您只需使用以下命令注册序列化器:

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Person.class, new PersonSerializer());

And finally serialize your object as usual with gson.toJson method... 最后使用gson.toJson方法照常序列化您的对象...

I'm not sure if it's the best approach, but it's pretty straightforward... Otherwise you can take a look at Gson's excusion strategies ... 我不确定这是否是最好的方法,但这很简单...否则,您可以看看Gson的原谅策略 ...

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

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