Change JsonProperty (Access.WRITE_ONLY) programmatically

Codehai :

My Java objects have some fields that are annotated write only because they should not be send over a REST interface to the users.

  @JsonProperty(access = Access.WRITE_ONLY)
  private List<Integer> integerList;

Now I am trying to implement an admin-controller, where these fields should be sent. My question is, can I change the property with code in my controller or do I have to create new objects for this purpose where the target fields are not annotated anymore. I think this wouldn't be a clean solution so I guess I am missing some FasterXML Jackson feature here..

Thanks in advance for your help,

Codehai

Nitzanoh :

Yes, there is a much simpler way to do that using fasterXML annotation.

Create filter using fasterXML, and define the fields you wish to filter. The list of properties can be defined hardcoded, or calculated in runtime. For example in admin controller the filter list is empty(or partial), and regular controller the filter is list contain values: The class you are serializing:

@JsonFilter("PersonFilter")
public class Person
{
   private List<Integer> integerList; 
   private Integer creditCardNUmber;
   private String firstName;
   private String lastName;

public static FilterProvider getFilter(){
    Set<String> fieldsToFilter= new HashSet<>(Arrays.asList("creditCardNUmber","integerList");
    SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
            .serializeAllExcept(fieldsToFilter);
    FilterProvider filters = new SimpleFilterProvider()
            .addFilter("PersonFilter", theFilter);
    return filters;
}
}

When you serialize the object you can use predefined list of properties to filter (public static FilterProvider getFilter(){..} ), or define them in runtime.

public static String GetObjectAsStringWithFilter(FilterProvider filters, Object jsonObject)
{
    if (jsonObject == null)
    {
        return null;
    }
    String objectAsString = null;
    try
    {
        objectAsString = objectMapper.writer(filters).writeValueAsString(jsonObject);
    }
    catch (Exception e)
    {
        ...
    }

    return objectAsString;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=462949&siteId=1