简体   繁体   English

Spring Jackson JsonViews-获取基于JsonView的字段

[英]Spring Jackson JsonViews - Get Fields based on JsonView

I've got an entity with a number of fields and with a JsonView specified: 我有一个包含多个字段并指定了JsonView的实体:

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. 由于字段istest设置为SystemView ,所以我不希望客户端更新该字段。

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 ). 我已经阅读了订单文章,必须先加载客户端,然后相应地更新参数(在我的情况下为clientIdname ),才能手动完成此操作。

Now I want to get a list of fields that I need to update (ie the fields marked with JsonView as Views.ClientView.class ). 现在,我想要获取需要更新的字段的列表(即,用JsonView标记为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. 但是, attributes返回时没有任何元素。

Is there a way to get this list of fields based on the View? 有没有一种方法可以基于视图获取此字段列表?

You can try to access and inspect the annotations of fields in a class with Reflection likes: 您可以尝试使用Reflection类访问并检查类中字段的注释:

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 . 在上面的示例中, annotatedFields将包含Client类中用JsonView注释的字段列表,其值包含Views.SystemView.class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM