2016-07-11 15 views
0

に基づいて取得:春ジャクソンJsonViews - フィールドは、私はフィールドの数と実体を持って、JsonViewで指定した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; 
    ......... 

} 

を次のようにビューが定義されています。

public class Views { 

    public interface SystemView extends ClientView { 
    } 

    public interface ClientView { 
    } 
} 

私はまた、クライアントを更新するための簡単なコントローラを持っています。フィールドistestSystemViewに設定されているため、クライアントはそのフィールドを更新したくありません。

私は、クライアントを最初にロードし、それに応じて(私の場合はclientIdname)対応するパラメータを更新することによって手動で行う必要がある投稿を読みました。

ここでは、更新する必要があるフィールドのリスト(JsonViewと記されているフィールドはViews.ClientView.class)を取得します。私は、次のことを試してみたが、それは働いていない:

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

をしかし、attributesは、任意の要素なしに戻っています。

ビューに基づいてこのフィールドのリストを取得する方法はありますか?あなたがReflection好きで、クラス内のフィールドの注釈にアクセスし、検査しようとすることができる

答えて

0

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); 
    } 
} 

上記の例では、annotatedFieldsは値でJsonViewで注釈が付けClientクラスのフィールドのリストが含まれますViews.SystemView.classを含みます。

関連する問題