Search code examples
javajson-lib

How to exclude properties from bean to json at runtime


I want to exclude properties from bean to json using json-lib at runtime.
How can i do it?
I have tried using propertyFilter of jsonconfig, I am not sure if its at runtime.


Solution

  • Here's a code-snippet based on the sample code at Filtering Properties in JSON Advanced Features that might be useful.

    PropertyFilter pf = new PropertyFilter(){  
       public boolean apply( Object source, String name, Object value ) {  
          if( value != null && Number.class.isAssignableFrom( value.getClass() ) ){  
             return true;  
          }  
          return false;  
       }  
    };
    
    PrimitiveBean bean = new PrimitiveBean();  
    JsonConfig jsonConfig = new JsonConfig();  
    jsonConfig.setJsonPropertyFilter(pf); 
    JSONObject json = JSONObject.fromObject( bean, jsonConfig );  
    

    You could set a different function to the JSON Config before you serialize the bean into a JSON object... in case that's what you meant by run time.