Excluding empty properties

Help
2008-07-22
2013-04-29
  • Neil Erdwien
    Neil Erdwien
    2008-07-22

    I've got a set of beans I want to serialize--that part works.  However, I'd like to exclude properties that are empty strings.  The JSON has a bunch of "attribute":"" pairs that I'd like to omit.

    My first try:

      JsonConfig jsonConfig = new JsonConfig();
      jsonConfig.setJsonPropertyFilter( new PropertyFilter(){
         public boolean apply(Object source, String name, Object value) {
                System.out.println(name);
                System.out.println(value);
            if (value==null  ||  (value instanceof String) && ((String)value).equals("")) {
               return true;
            }
            return false;
         }
      });

      JSON json = JSONSerializer.toJSON(matches, jsonConfig);
      json.write(out);

    did't work.  In fact, I got no console messages at all, so I'm presuming the filter wasn't called.

    Any hints?

    Thanks.

     
    • aalmiray
      aalmiray
      2008-07-22

      Neil,

      Judging by the filter code it looks like it might work. Are you sure the input strings are really 'empty'?
      Filters are the third option you have to exclude a property, the following two are evaluated first in this order
      1) exclusion list via jsonConfig.setExcludes()
      2) a registered JsonBeanProcessor, which is a custom serializer after all

      Once those two options are checked, then the serialization mechanism will lookup a PropertyDescriptor for each property, if the property does have a read method, then the filter is evaluated. Can you show us more about the serialized beans (matches), the provided code is not enough to reach a conclusive diagnosis, thanks!

      Andres