我不确定我是否能完全理解您的问题,但是据我所知,您可以执行类似的操作来实现不同的序列化。
创建一个自定义批注以保存所有可能的不同序列化选项:
@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface CustomJsonProperty { String propertyName(); String format(); @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @documented @interface List { CustomJsonProperty[] value(); }}相应地注释您的班级:
@JsonSerialize(using = CustomJsonPropertySerializer.class)public class Bar { @CustomJsonProperty.List({ @CustomJsonProperty(propertyName = "first-name", format = "A"), @CustomJsonProperty(propertyName = "firstName", format = "B") }) private String firstName; @CustomJsonProperty.List({ @CustomJsonProperty(propertyName = "last-name", format = "A"), @CustomJsonProperty(propertyName = "lastName", format = "B") }) private String lastName; @CustomJsonProperty.List({ @CustomJsonProperty(propertyName = "gender-x", format = "A"), @CustomJsonProperty(propertyName = "gender", format = "B") }) private String gender; @JsonIgnore private String format; //getters & setters}创建一个自定义序列化器来解释您的新注释:
public class CustomJsonPropertySerializer extends JsonSerializer<Bar> { @Override public void serialize(Bar bar, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeStartObject(); Field[] fields = bar.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); Object value = null; try { value = field.get(bar); } catch (IllegalAccessException e) { e.printStackTrace(); } if (field.isAnnotationPresent(CustomJsonProperty.List.class)) { CustomJsonProperty[] properties = field.getAnnotation(CustomJsonProperty.List.class).value(); CustomJsonProperty chosenProperty = null; for (CustomJsonProperty c : properties) { if (c.format().equalsIgnoreCase(bar.getFormat())) { chosenProperty = c; break; } } if (chosenProperty == null) { //invalid format given, use first format then chosenProperty = properties[0]; } jsonGenerator.writeStringField(chosenProperty.propertyName(), value.toString()); } } jsonGenerator.writeEndObject(); }}现在,您可以考虑属性名称的不同格式来序列化对象:
public static void main(String[] args) throws IOException { Bar bar1 = new Bar("first", "last", "m", "A"); Bar bar2 = new Bar("first", "last", "m", "B"); ObjectMapper mapper = new ObjectMapper(); String json1 = mapper.writevalueAsString(bar1); String json2 = mapper.writevalueAsString(bar2); System.out.println(json1); System.out.println(json2);}输出:
{"first-name":"first","last-name":"last","gender-x":"m"}{"firstName":"first","lastName":"last","gender":"m"}当然,上述序列化程序仅适用于Bar对象,但是可以通过
abstract StringgetFormat();在父类上使用继承并更改自定义序列化器以接受父类而不是Bar 来轻松解决。
也许有比创建自己的东西更简单的方法,但是我不知道。让我知道是否有不清楚的地方,我可以再次详细说明。



