Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change JsonProperty (Access.WRITE_ONLY) programmatically

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

like image 982
Codehai Avatar asked Aug 31 '17 20:08

Codehai


1 Answers

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;
}
like image 189
Nitzanoh Avatar answered Nov 06 '22 03:11

Nitzanoh