Java Gson Exclude fields during serialization

前端 未结 7 1627
走了就别回头了
走了就别回头了 2020-12-10 01:48

I have a ConfigInstance class which contains a password and a password_hash. Now I want to serialize the object using gson but exclude

7条回答
  •  误落风尘
    2020-12-10 02:09

    Here's a very simple solution with just one line of code, without any @Expose annotation or exclusion strategy.

    The default behaviour that is implemented in Gson is that null object fields are ignored. So, all you need to do is set the password field to null before serializing.

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

提交回复
热议问题