I'm trying to create a custom serializer for a class A's instance variable.
The problem is that the variable is of a "standard" built in type ( List<List<String>>
)
I found out that you can in theory create a custom serializer for a type to be used ONLY within your class using mix-ins ; so in theory if I could create a custom serializer for List<List<String>>
, I could mix-in it into class A that way.
But how do I create a custom serializer for List<List<String>>
?
I think it can be something like this. I don't know the logic you want to use, when serialize, so I wrote simple json array[][]
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();
}
}
As example without mixIn
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()));
}
The output is
{"myStrings":[["a","b","c"],["d","f","g"]]}
Is that what you are trying to do?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.