想要只包含Genson映射到JSON的对象的某些字段

时间:2022-08-23 08:10:46

My Pojo class contains 50 fields and I need to convert only 10 fields to json.

我的Pojo类包含50个字段,我只需要将10个字段转换为json。

Genson genson = new Genson.Builder().include("address4", User.class).create();
String json = genson.serialize(user);

"include()" method doesn't seem to be working. Kindly help.

“include()”方法似乎不起作用。请帮助。

2 个解决方案

#1


1  

Genson genson = new Genson.Builder()
                 .exclude(Object.class)//this excludes all object types
                 .include("address4", User.class).create();//then add only required fields
String json = genson.serialize(user);

#2


0  

An option would be to disable by default all properties and include selectively those you want like this:

一个选项是默认情况下禁用所有属性,并选择性地包含你想要的那些:

new GensonBuilder()
  .useFields(false)
  .useMethods(false)
  .include("address4", User.class)
  .create();

Note that I think you can also use @JsonProperty annotation on the fields you want to include instead of including them via the GensonBuilder.

请注意,我认为您还可以在要包含的字段上使用@JsonProperty注释,而不是通过GensonBuilder包含它们。

If you are feeling your self of contributing to the lib, you could also improve the PropertyFilter class to support regular expressions for the field name or by adding another method that would be excludeAll(Class clazz)/includeAll(Class clazz), that would exclude all properties from this class. I opened this issue to track this feature.

如果您觉得自己有助于lib,那么您还可以改进PropertyFilter类以支持字段名称的正则表达式,或者添加另一个将排除的所有方法:excludeAll(Class clazz)/ includeAll(Class clazz)此类中的所有属性。我打开此问题来跟踪此功能。

#1


1  

Genson genson = new Genson.Builder()
                 .exclude(Object.class)//this excludes all object types
                 .include("address4", User.class).create();//then add only required fields
String json = genson.serialize(user);

#2


0  

An option would be to disable by default all properties and include selectively those you want like this:

一个选项是默认情况下禁用所有属性,并选择性地包含你想要的那些:

new GensonBuilder()
  .useFields(false)
  .useMethods(false)
  .include("address4", User.class)
  .create();

Note that I think you can also use @JsonProperty annotation on the fields you want to include instead of including them via the GensonBuilder.

请注意,我认为您还可以在要包含的字段上使用@JsonProperty注释,而不是通过GensonBuilder包含它们。

If you are feeling your self of contributing to the lib, you could also improve the PropertyFilter class to support regular expressions for the field name or by adding another method that would be excludeAll(Class clazz)/includeAll(Class clazz), that would exclude all properties from this class. I opened this issue to track this feature.

如果您觉得自己有助于lib,那么您还可以改进PropertyFilter类以支持字段名称的正则表达式,或者添加另一个将排除的所有方法:excludeAll(Class clazz)/ includeAll(Class clazz)此类中的所有属性。我打开此问题来跟踪此功能。