在Jackson JSON中,使用SerializationFeature.WRAP_ROOT_VALUE作为注解是什么意思?

20

是否有一种方法可以将SerializationFeature.WRAP_ROOT_VALUE的配置作为根元素上的注释来使用,而不是使用ObjectMapper

例如,我有:

@JsonRootName(value = "user")
public class UserWithRoot {
    public int id;
    public String name;
}

使用ObjectMapper:

@Test
public void whenSerializingUsingJsonRootName_thenCorrect()
  throws JsonProcessingException {
    UserWithRoot user = new User(1, "John");

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
    String result = mapper.writeValueAsString(user);

    assertThat(result, containsString("John"));
    assertThat(result, containsString("user"));
}

结果:

{
    "user":{
        "id":1,
        "name":"John"
    }
}

有没有一种方法可以将SerializationFeature作为注释而不是在objectMapper上进行配置?

使用依赖项:

<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.7.2</version>
</dependency>

也许是这个:https://dev59.com/DnE95IYBdhLWcg3wJKl_#31158706 参见:https://github.com/FasterXML/jackson-annotations/issues/33 - assylias
@assylias 是的,我也看到了那个答案。但是不知道如何将其转换为小驼峰式命名法。需要 user 而不是 User。不确定是否可能。 - Patrick
3个回答

40
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test2 {
    public static void main(String[] args) throws JsonProcessingException {
        UserWithRoot user = new UserWithRoot(1, "John");

        ObjectMapper objectMapper = new ObjectMapper();

        String userJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);

        System.out.println(userJson);
    }

    @JsonTypeName(value = "user")
    @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
    private static class UserWithRoot {
        public int id;
        public String name;
    }
}

@JsonTypeName@JsonTypeInfo 一起使用可以实现此功能。

{
  "user" : {
    "id" : 1,
    "name" : "John"
  }
}

2
谢谢您,我简直不敢相信只是包装一个响应竟然如此复杂。 - Sean
3
@Sean - 真的,这很复杂,需要时间来适应。他们本可以想出类似于@JsonWrapper@JsonRootValue这样的东西,它将采用包装器的名称。 - isank-a
有没有办法支持两种格式 - 带根或不带根? - Tushar Patel
1
为了这个解决方案花费了很多时间。@JsonRootName 看起来很有前途,但是没有起作用。 - Sylvester
谢谢您!同时它也适用于反序列化。 - Dimio

0

我认为这已被请求为:

 https://github.com/FasterXML/jackson-databind/issues/1022

所以,如果有人想要挑战并有机会让许多用户感到满意(这肯定是一件好事),那么就可以抓住这个机会 :)

除此之外,值得注意的一点是,您可以使用ObjectWriter来启用/禁用SerializationFeature

String json = objectMapper.writer()
   .with(SerializationFeature.WRAP_ROOT_VALUE)
   .writeValueAsString(value);

如果有时需要使用它,有时不需要(ObjectMapper设置在初始构建和配置后不应更改)。


-1

您可以按照以下方式使用它,这样该属性将应用于整个objectMapper的使用。

static {
    objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接