【问题标题】:SerializationFeature.WRAP_ROOT_VALUE as annotation in jackson jsonSerializationFeature.WRAP_ROOT_VALUE 作为杰克逊 json 中的注释
【发布时间】:2016-10-19 08:17:26
【问题描述】:

有没有办法将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>

【问题讨论】:

标签: java json serialization jackson


【解决方案1】:

我认为这是被要求的:

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

因此,如果有人想要挑战并有机会让许多用户感到高兴(这是肯定的好东西),那就来抢吧:)

除了一件值得注意的小事之外,您可以使用ObjectWriter 来启用/禁用SerializationFeatures。

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

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

【讨论】:

    【解决方案2】:
    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"
      }
    }
    

    【讨论】:

    • 谢谢你,我无法相信仅仅包装回复是多么复杂。
    • @Sean - 确实如此,它很复杂,需要时间来适应。他们本可以想出类似@JsonWrapper@JsonRootValue 之类的东西,它们将采用包装器的名称。
    • 有没有一种方法可以同时支持两种格式 - 有或没有 root?
    • 为此解决方案花费了大量时间。 @JsonRootName 看起来很有希望,但没有奏效。
    • 谢谢你!它也适用于反序列化。
    猜你喜欢
    • 2016-01-03
    • 2012-11-04
    • 2016-09-25
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多