0

I've got an entity with a number of fields and with a JsonView specified:

public class Client {

   @JsonView(Views.ClientView.class)
   @Column(name = "clientid")
   private long clientId;

   @JsonView(Views.ClientView.class)
   @Column(name = "name")
   private String name

   @JsonView(Views.SystemView.class)
   @Column(name = "istest")
   private boolean istest;
   .........

}

The views are defined as follows:

public class Views {

  public interface SystemView extends ClientView {
  }

  public interface ClientView {
  }
}

I also have a simple controller in order to update the client. Since the field istest is set to SystemView, I don't want the client to update that field.

I've read in order posts, that this has to be done manually by first loading the client and than updating the parameters accordingly (in my case clientId and name).

Now I want to get a list of fields that I need to update (i.e. the fields marked with JsonView as Views.ClientView.class). I've tried the following but it's not working:

ObjectReader reader = objectMapper.readerWithView(SystemView.class);
ContextAttributes attributes = reader.getAttributes();

But, attributes is returning without any elements.

Is there a way to get this list of fields based on the View?

cgval
  • 1,096
  • 5
  • 14
  • 31

1 Answers1

0

You can try to access and inspect the annotations of fields in a class with Reflection likes:

List<Field> annotatedFields = new ArrayList<>();
Field[] fields = Client.class.getDeclaredFields();
for (Field field : fields) {
    if (!field.isAnnotationPresent(JsonView.class)) {
        continue;
    }
    JsonView annotation = field.getAnnotation(JsonView.class);
    if (Arrays.asList(annotation.value()).contains(Views.SystemView.class)) {
        annotatedFields.add(field);
    }
}

In the above example, annotatedFields will contain a list of fields in Client class annotated with JsonView with a value contains Views.SystemView.class.

Wilson
  • 11,339
  • 2
  • 29
  • 33