ジャクソン–カスタムシリアライザー
1. 概要
このクイックチュートリアルでは、Custom Serializerを使用してJackson2でJavaエンティティをシリアル化する方法を示します。
さらに深く掘り下げてother cool things you can do with the Jackson 2を学びたい場合は、the main Jackson tutorialに進んでください。
2. オブジェクトグラフの標準シリアル化
2つの単純なエンティティを定義し、Jacksonがカスタムロジックなしでこれらをシリアル化する方法を見てみましょう。
public class User {
public int id;
public String name;
}
public class Item {
public int id;
public String itemName;
public User owner;
}
それでは、ItemエンティティをUserエンティティでシリアル化しましょう。
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = new ObjectMapper().writeValueAsString(myItem);
これにより、両方のエンティティの完全なJSON表現が生成されます。
{
"id": 1,
"itemName": "theItem",
"owner": {
"id": 2,
"name": "theUser"
}
}
3. ObjectMapperのカスタムシリアライザー
さて、上記のlet’s simplify the JSON outputは、Userオブジェクト全体ではなく、Userのidのみをシリアル化することによって;次のより単純なJSONを取得したいと思います。
{
"id": 25,
"itemName": "FEDUfRgS",
"owner": 15
}
簡単に言えば、Itemオブジェクトに対してdefine a custom Serializerを実行する必要があります。
public class ItemSerializer extends StdSerializer- {
public ItemSerializer() {
this(null);
}
public ItemSerializer(Class
- t) {
super(t);
}
@Override
public void serialize(
Item value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeStringField("itemName", value.itemName);
jgen.writeNumberField("owner", value.owner.id);
jgen.writeEndObject();
}
}
ここで、このカスタムシリアライザーをItemクラスのObjectMapperに登録し、シリアル化を実行する必要があります。
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(module);
String serialized = mapper.writeValueAsString(myItem);
これで、Item→UserエンティティのよりシンプルなカスタムJSONシリアル化が可能になりました。
4. クラスのカスタムシリアライザー
ObjectMapperの代わりに、register the serializer directly on the classを使用することもできます。
@JsonSerialize(using = ItemSerializer.class)
public class Item {
...
}
ここで、standard serializationを実行する場合:
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = new ObjectMapper().writeValueAsString(myItem);
@JsonSerializeで指定されたシリアライザーによって作成されたカスタムJSON出力を取得します。
{
"id": 25,
"itemName": "FEDUfRgS",
"owner": 15
}
これは、ObjectMapperに直接アクセスして構成できない場合に役立ちます。
5. 結論
この記事では、シリアライザーを使用して、Jackson 2でカスタムJSON出力を取得する方法を説明しました。
これらすべての例とコードスニペットcan be found on GitHubの実装–これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。