我从您对 Vidya 解决方案的评论中收集到,您寻求比默认绑定更多的灵活性。
Jackson 允许您创建自己的自定义序列化程序。例如:
public class Person {
private String name;
private int age;
private List<String> parentsName;
private List<String> childrenNames;
public Person(String name, List<String> parentsName) {
this(name, parentsName, -1, Collections.<String>emptyList());
}
public Person(String name, List<String> parentsName, int age) {
this(name, parentsName, age, Collections.<String>emptyList());
}
public Person(String name, List<String> parentsName, int age, List<String> childrenNames) {
this.name = name;
this.age = age;
this.parentsName = parentsName;
this.childrenNames = childrenNames;
}
private void serialize(JsonGenerator generator, SerializerProvider arg2) throws IOException {
generator.writeStartObject();
generator.writeObjectField("name", name);
if (age >= 0)
generator.writeNumberField("age", age);
// start family subset
generator.writeObjectFieldStart("family");
generator.writeArrayFieldStart("parents_name");
for (String parent : parentsName) {
generator.writeObject(parent);
}
generator.writeEndArray();
generator.writeObjectField("children", (childrenNames.isEmpty() ? "no" : "yes"));
generator.writeArrayFieldStart("children_names");
for (String child : childrenNames) {
generator.writeObject(child);
}
generator.writeEndArray();
generator.writeEndObject();
// end family subset
generator.writeEndObject();
}
public static JsonSerializer<Person> createJsonSerializer() {
return new JsonSerializer<Person>() {
@Override
public void serialize(Person me, JsonGenerator generator, SerializerProvider arg2) throws IOException, JsonProcessingException {
me.serialize(generator, arg2);
}
};
}
public static void main(String[] args) throws IOException {
List<String> parentsName = Arrays.<String>asList("David", "Susan");
List<String> childrenNames = Arrays.<String>asList("Peter", "Mary");
Person person = new Person("John", parentsName, 40, childrenNames);
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("PersonModule", new Version(1, 0, 0, null));
simpleModule.addSerializer(Person.class, Person.createJsonSerializer());
// pretty output for debugging
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
mapper.registerModule(simpleModule);
System.out.println("Person json: ");
System.out.println(mapper.writeValueAsString(person));
}
}
这通过两种方式为您提供了更大的灵活性:
您可以在序列化中应用条件逻辑
您可以有多个自定义序列化程序
缺点相当明显