JSON嵌套属性未嵌套

时间:2015-05-27 13:48:29

标签: java json rest jackson

如果我有例如

,那可能吗?
class DefaultFruit {
  taste: String
}

class Fruit {

  fruit: DefaultFruit
  color: String
}

提供一些注释@JSON注释,用于转换对象结构

为:

{
color: "",
taste: "",
}

1 个答案:

答案 0 :(得分:2)

是的,您可以使用@JsonUnwrapped注释fruit属性/字段,并且DefaultFruit属性将与Fruit属性一起序列化/解除分类。

public static class DefaultFruit {
    public String taste;
}

public static class Fruit {
    @JsonUnwrapped
    public DefaultFruit fruit;
    public String color;
}

@Test
public void serialize_unwrapped() throws Exception {
    Fruit fruit = new Fruit();
    fruit.color = "red";
    fruit.fruit = new DefaultFruit();
    fruit.fruit.taste = "sweet";
    assertThat(mapper.writeValueAsString(fruit),
               equalTo("{\"taste\":\"sweet\",\"color\":\"red\"}"));
}