JavaオブジェクトからJSON文字列を生成したい
public class Resource {
String name;
List<Item> items;
public String resourceAsJson(Resource resource) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(resource);
}
場所アイテム
public class Item {
Map<String, String> systemFields;
Map<String, String> dataFields;
}
この時点でのJSON文字列の形式は次のとおりです。
{
"name": "Person",
"items": [
{
"systemFields": {
"systemField1": "xxx",
"systemField2": "xxx",
"systemField3": "x"
},
"dataFields": {
"dataField1": "xxx",
"dataField2": "xxx",
"dataField3": "x"
}
}
]
}
私が取得しようとしているのは、JSONの異なる形式です(アイテムを省略し、1つのJsonテーブルに「システムフィールド」「データフィールド」があります)
{
"Person":[
{
"systemField1": "xxx",
"systemField2": "xxx",
"systemField3": "Warsaw",
"dataField1": "xxx",
"dataField2": "xxx",
"dataField3": "xxx"
}
]
}
モデルを変更せずにジャクソンでこれを行う方法はありますか?
このような場合、のデフォルトの表現がPOJO
カスタムシリアライザーの実装に必要なものではありません。あなたの場合、それらは以下のようになります:
class ResourceJsonSerializer extends JsonSerializer<Resource> {
@Override
public void serialize(Resource value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeFieldName(value.getName());
gen.writeObject(value.getItems());
gen.writeEndObject();
}
}
class ItemJsonSerializer extends JsonSerializer<Item> {
@Override
public void serialize(Item value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
writeMap(value.getSystemFields(), gen);
writeMap(value.getDataFields(), gen);
gen.writeEndObject();
}
private void writeMap(Map<String, String> map, JsonGenerator gen) throws IOException {
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
gen.writeStringField(entry.getKey(), entry.getValue());
}
}
}
}
com.fasterxml.jackson.databind.annotation.JsonSerialize
アノテーションを使用してそれらを登録できます。
@JsonSerialize(using = ResourceJsonSerializer.class)
class Resource {
そして:
@JsonSerialize(using = ItemJsonSerializer.class)
class Item {
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加