Jackson filters fields without annotations

I tried to filter specific fields from serialization through SimpleBeanPropertyFilterusing the following (simplified) code:

public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();

    SimpleFilterProvider filterProvider = new SimpleFilterProvider().addFilter("test",
            SimpleBeanPropertyFilter.filterOutAllExcept("data1"));
    try {
        String json = mapper.writer(filterProvider).writeValueAsString(new Data());

        System.out.println(json); // output: {"data1":"value1","data2":"value2"}

    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

private static class Data {
    public String data1 = "value1";
    public String data2 = "value2";
}

Us I use SimpleBeanPropertyFilter.filterOutAllExcept("data1"));I expected that the generated serialized Json string contains only {"data1":"value1"}, however I get {"data1":"value1","data2":"value2"}.

How to create a temporary entry that matches the specified filter (ObjectMapper cannot be reconfigured in my case).

Note. Due to the usage scenario in my application, I can only accept responses that do not use Jackson annotations.

+1
source share
4 answers

Usually you add a comment to the class Datato apply the filter:

@JsonFilter("test")
class Data {

, . mix-ins, Data.

@JsonFilter("test")
class DataMixIn {}

Mixins ObjectMapper, , . ObjectMapper , . ObjectMapper, . .

ObjectMapper myMapper = mapper.copy();
myMapper.addMixIn(Data.class, DataMixIn.class);

ObjectMapper

String json = myMapper.writer(filterProvider).writeValueAsString(new Data());
System.out.println(json); // output: {"data1":"value1"}
+1

, , , bean, , :

@JsonFilter("test")
public class Data {
    public String data1 = "value1";
    public String data2 = "value2";
}

OP , , bean, , , , , , .

Map<String, Object> map = new HashMap<String, Object>();
map.put("data1", obj.getData1());
...
// do the serilization on the map object just created.

, , . , bean , , :

protected Map<String, Object> transBean2Map(Object beanObj){
        if(beanObj == null){
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();


                if (!key.equals("class")
                        && !key.endsWith("Entity")
                        && !key.endsWith("Entities")
                        && !key.endsWith("LazyInitializer")
                        && !key.equals("handler")) {


                    Method getter = property.getReadMethod();

                    if(key.endsWith("List")){
                        Annotation[] annotations = getter.getAnnotations();
                        for(Annotation annotation : annotations){
                            if(annotation instanceof javax.persistence.OneToMany){
                                if(((javax.persistence.OneToMany)annotation).fetch().equals(FetchType.EAGER)){
                                    List entityList = (List) getter.invoke(beanObj);
                                    List<Map<String, Object>> dataList = new ArrayList<>();
                                    for(Object childEntity: entityList){
                                        dataList.add(transBean2Map(childEntity));
                                    }
                                    map.put(key,dataList);
                                }
                            }
                        }
                        continue;
                    }

                    Object value = getter.invoke(beanObj);

                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            Logger.getAnonymousLogger().log(Level.SEVERE,"transBean2Map Error " + e);
        }
        return map;
    }

Google Gson / JSON. , , .

bean :

@Since(GifMiaoMacro.GSON_SENSITIVE) //mark the field as sensitive data and will not export to JSON
private boolean firstFrameStored; // won't export this field to JSON.

, :

 public static final double GSON_SENSITIVE = 2.0f;
 public static final double GSON_INSENSITIVE = 1.0f;

Gson , @Since , .

- , json, .. , . json :

 private static Gson gsonInsensitive = new GsonBuilder()
            .registerTypeAdapter(ObjectId.class,new ObjectIdSerializer()) // you can omit this line and the following line if you are not using mongodb
            .registerTypeAdapter(ObjectId.class, new ObjectIdDeserializer()) //you can omit this
            .setVersion(GifMiaoMacro.GSON_INSENSITIVE)
            .disableHtmlEscaping()
            .create();

public static String toInsensitiveJson(Object o){
    return gsonInsensitive.toJson(o);
}

:

 String jsonStr = StringUtils.toInsensitiveJson(yourObj);

Gson , , JSON-/ Java, , Gson , .

0

:

public Class User {
    private String name = "abc";
    private Integer age = 1;
    //getters
}

@JsonFilter("dynamicFilter")
public class DynamicMixIn {
}

User user = new User();
String[] propertiesToExclude = {"name"};
ObjectMapper mapper = new ObjectMapper()
      .addMixIn(Object.class, DynamicMixIn.class);
FilterProvider filterProvider = new SimpleFilterProvider()
                .addFilter("dynamicFilter", SimpleBeanPropertyFilter.filterOutAllExcept(propertiesToExclude));
        mapper.setFilterProvider(filterProvider);

mapper.writeValueAsString(user); // {"name":"abc"}

DynamicMixIn MixInByPropName

@JsonIgnoreProperties(value = {"age"})
public class MixInByPropName {
}

ObjectMapper mapper = new ObjectMapper()
      .addMixIn(Object.class, MixInByPropName.class);

mapper.writeValueAsString(user); // {"name":"abc"}

. User, Object.class addMixIn User.class

, MixInByType

@JsonIgnoreType
public class MixInByType {
}

ObjectMapper mapper = new ObjectMapper()
      .addMixIn(Integer.class, MixInByType.class);

mapper.writeValueAsString(user); // {"name":"abc"}
0

- MixIns . :

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector(){
    @Override
    public boolean hasIgnoreMarker(final AnnotatedMember m) {

    List<String> exclusions = Arrays.asList("field1", "field2");
    return exclusions.contains(m.getName())|| super.hasIgnoreMarker(m);
    }
});
0

All Articles