可以使用哪种Java数据结构序列化到具有一组子对象的以下Json?
示例:
{
"John": {
"Type": "Person",
"age": 30,
"Sean": {
"Type": "child",
"age": 3
},
"Julian": {
"Type": "child",
"age": 4
}
},
"Paul": {
"Type": "Person",
"age": 64,
"Stella": {
"Type": "child",
"age": 10
},
"James": {
"Type": "child",
"age": 12
}
}
}
写约翰和保罗可以通过:Map<String,Person>
完成,但我不知道如何在没有'children'属性的情况下嵌套Child。
示例:
{
"John": {
"Type": "Person",
"age": 30,
"children": {
"Sean": {
"Type": "child",
"age": 3
},
"Julian": {
"Type": "child",
"age": 4
}
}
}
}
我不确定是否相关,但是正在使用Gson创建Json文件
我不确定杰克逊有可能用GSON做到这一点。
使用GSON,您可以尝试自定义JsonSerializer
,看起来可能像这样:
private static class PersonTypeSerializer implements JsonSerializer<Person> {
@Override
public JsonElement serialize(Person person, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject personJson = personToJson(person);
for (Map.Entry<String, Person> child : person.getChildren().entrySet()) {
personJson.add(child.getKey(), personToJson(child.getValue()));
}
return personJson;
}
private static JsonObject personToJson(Person person) {
JsonObject personJson = new JsonObject();
personJson.addProperty("Type", person.getType());
personJson.addProperty("age", person.getAge());
return personJson;
}
}
[提供类型"Person"
和"child"
都由Person
类表示。如果没有修改,应该很容易修改。