0
@JsonViewの異なるクラスを使用してフィールドを表示/非表示するだけでなく、各フィールドで個別に使用されるビューに応じて異なる名前(@JsonPropertyなど)を定義する方法はありますか?ジャクソン@JsonViewと@JsonPropertyの組み合わせ
greets & thx! チーム
@JsonViewの異なるクラスを使用してフィールドを表示/非表示するだけでなく、各フィールドで個別に使用されるビューに応じて異なる名前(@JsonPropertyなど)を定義する方法はありますか?ジャクソン@JsonViewと@JsonPropertyの組み合わせ
greets & thx! チーム
私の解決策には、Jackson Mixin機能が含まれます。
別の@jsonPropertyアノテーションを配置するために同じビュークラスを使用しました。これは別のクラスよりもはるかに便利ですが、ビューの継承を使用することはできません。これが必要な場合は、@ jsonPropertyアノテーションを保持する別のクラスを作成し、それに応じてmixinモジュールを変更する必要があります。ここ
をシリアル化することを目的とする。
public class Bean
{
@JsonView({Views.Public.class, Views.Internal.class})
public String name;
@JsonView(Views.Internal.class)
public String ssn;
}
JSONプロパティの注釈付きビュー
public class Views
{
public static class Public {
@JsonProperty("public_name")
public String name;
}
public static class Internal {
@JsonProperty("internal_name")
public String name;
}
}
ジャクソンによって必要とされるミックスインモジュール:
@SuppressWarnings("serial")
public class PublicModule extends SimpleModule
{
public PublicModule() {
super("PublicModule");
}
@Override
public void setupModule(SetupContext context)
{
context.setMixInAnnotations(Bean.class, Views.Public.class);
}
}
@SuppressWarnings("serial")
public class InternalModule extends SimpleModule
{
public InternalModule() {
super("InternalModule");
}
@Override
public void setupModule(SetupContext context)
{
context.setMixInAnnotations(Bean.class, Views.Internal.class);
}
}
試験方法:
public static void main(String[] args)
{
Bean bean = new Bean();
bean.name = "my name";
bean.ssn = "123-456-789";
ObjectMapper mapper = new ObjectMapper();
System.out.println(args[0] + ": ");
try {
if (args[0].equals("public")) {
mapper.registerModule(new PublicModule());
mapper.writerWithView(Views.Public.class).writeValue(System.out, bean);
} else {
mapper.registerModule(new InternalModule());
mapper.writerWithView(Views.Internal.class).writeValue(System.out, bean);
}
} catch (IOException e) {
e.printStackTrace();
}
}
二つの別々の呼び出しで出力:
public:
{"public_name":"my name"}
internal:
{"ssn":"123-456-789","internal_name":"my name"}