Java – change jsonproperty programmatically (access. Write_only)
My java object has some comments that are only written to fields because they should not be sent to the user through the rest interface
@JsonProperty(access = Access.WRITE_ONLY) private List<Integer> integerList;
Now I'm trying to implement an admin controller, which should send these fields My question is, can I use the code in the controller to change properties, or must I create a new object for this purpose and the target field is no longer annotated I don't think this is a clean solution, so I think I missed some fasterxml Jackson features here
Thank you for your help,
Codehai
Solution
Yes, there is an easier way to use fasterxml annotations
Create a filter using fasterxml and define the fields to filter Attribute lists can be defined by hard coding or calculated at run time For example, in the admin controller, the filter list is empty (or partial), while the general controller filter list contains the value: the class you want to serialize:
@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 serializing objects, you can use the predefined attribute list for filtering (public static filterprovider getfilter() {..}), Or define them at run time
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; }