这似乎是您之前问题的延续。因此,除了@JsonUnwrapped
按照答案中的说明使用之外,您还需要@JsonProperty
在声明它的类中添加字段。修改前面的答案@JsonProperty
给你这个:
@RunWith(JUnit4.class)
public class Sample {
@Test
public void testName() throws Exception {
SampleClass sample = new SampleClass("value1", "value2", new SubClass("value4", "value5", new SubSubClass("value7")));
new ObjectMapper().writeValue(System.out, sample);
}
@JsonAutoDetect(fieldVisibility=Visibility.ANY)
public static class SampleClass {
private String prop1;
private String prop2;
@JsonUnwrapped
private SubClass prop3;
public SampleClass(String prop1, String prop2, SubClass prop3) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
}
}
@JsonAutoDetect(fieldVisibility=Visibility.ANY)
public static class SubClass {
@JsonProperty("prop4_new_name")
private String prop4;
private String prop5;
@JsonUnwrapped
private SubSubClass prop6;
public SubClass(String prop4, String prop5, SubSubClass prop6) {
this.prop4 = prop4;
this.prop5 = prop5;
this.prop6 = prop6;
}
}
@JsonAutoDetect(fieldVisibility=Visibility.ANY)
public static class SubSubClass{
@JsonProperty("prop7_new_name")
private String prop7;
public SubSubClass(String prop7) {
this.prop7 = prop7;
}
}
}
结果是:
{"prop2":"value2","prop5":"value5","prop7_new_name":"value7","prop4_new_name":"value4","prop1_new_name":"value1"}