我正在尝试为类 A 的实例变量创建自定义序列化程序。
问题是变量是内置类型的"标准"(List<List<String>>
(
我发现理论上你可以使用mix-in为仅在类中使用的类型创建自定义序列化程序;所以理论上,如果我可以为List<List<String>>
创建一个自定义序列化程序,我可以以这种方式将其混合到A类中。
但是如何为List<List<String>>
创建自定义序列化程序?
我认为它可以是这样的。我不知道序列化时你想使用的逻辑,所以我写了简单的json数组[][]
private static class ListListSerializer extends StdSerializer<List<List<String>>>{
protected ListListSerializer(Class<List<List<String>>> t) {
super(t);
}
protected ListListSerializer(){
this(null);
}
@Override
public void serialize(List<List<String>> lists, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartArray();
for (List<String> strings : lists) {
jsonGenerator.writeStartArray();
for (String string : strings) {
jsonGenerator.writeString(string);
}
jsonGenerator.writeEndArray();
}
jsonGenerator.writeEndArray();
}
}
作为没有混入的例子
private static class YourObject {
private List<List<String>> myStrings = new ArrayList<>();
public YourObject() {
List<String> a = Arrays.asList("a","b","c");
List<String> b = Arrays.asList("d","f","g");
myStrings.add(a);
myStrings.add(b);
}
@JsonSerialize(using = ListListSerializer.class)
public Object getMyStrings(){
return myStrings;
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(new YourObject()));
}
输出为
{"myStrings":[["a","b","c"],["d","f","g"]]}
这就是你想做的吗?