..ListコンテンツをJacksonでフラットなJSONオブジェクトにシリアライズするには?次のPOJOを考える
public class City {
private String title;
private List<Person> people;
}
...
public class Person {
private String name;
private int age;
}
私は次例 JSONにクラスのJacksonシリアル化インスタンスを聞かせしたいと思います:
{
"title" : "New York",
"personName_1" : "Jane Doe",
"personAge_1" : 42,
"personName_2" : "John Doe",
"personAge_2" : 23
}
JSON形式は、私が変更できない外部APIによって定義されています。
私はすでに私のようなカスタム・シリアライザをリストフィールドに注釈を付けることが分かっ:
...と、ここで私が試した基本的な実装です:
public class PeopleSerializer extends JsonSerializer<List<Person>> {
private static final int START_INDEX = 1;
@Override
public void serialize(List<Person> people,
JsonGenerator generator,
SerializerProvider provider) throws IOException {
for (int i = 0; i < people.size(); ++i) {
Person person = people.get(i);
int index = i + START_INDEX;
serialize(person, index, generator);
}
}
private void serialize(Person person, int index, JsonGenerator generator) throws IOException {
generator.writeStringField(getIndexedFieldName("personName", index),
person.getName());
generator.writeNumberField(getIndexedFieldName("personAge", index),
person.getAge());
}
private String getIndexedFieldName(String fieldName, int index) {
return fieldName + "_" + index;
}
}
をしかし、この
JsonGenerationException: Can not write a field name, expecting a value
私もジャクソンのConverterインターフェイスを使用してみましたが、ネストされたリストオブジェクトのアンラップには適していません。
私も@JsonUnwrapped
の承知していますが、リストを使用するように設計されていません。
関連記事
- Serialize List content in a flat structure in jackson json (Java)
- Jackson: How to add custom property to the JSON without modifying the POJO
- How to serialize only the ID of a child with Jackson
私は 'City'ためのシリアライザが書き込まれるため、これは、あなたが' City'クラスのために、あなたの 'JsonSerializer'を書くことがあると思いますフィールド名 'people'はカスタム' JsonSerializer'が値を書き込むことを期待しています。 –
@ug_私はそれを試み、 'City'クラスに' @JsonSerialize(using = CitySerializer.class) 'と注釈をつけました。カスタムシリアライザの中で、私は上記の 'PeopleSerializer'で行ったのと同様の' people'フィールドだけをシリアライズしました。同じエラーメッセージでシリアル化が失敗します。 – JJD
@JJD - オフチャンスでは、より簡単なアプローチがあります。あなたが解決しようとしている根本的な問題は何ですか?あなたのターゲットJSON構造が解析しやすくするケースは想像できません。 – AjahnCharles