SerializationFeature.WRAP_ROOT_VALUE as annotation in jackson json

前端 未结 1 556
感情败类
感情败类 2021-02-07 22:52

Is there a way to have the configuration of SerializationFeature.WRAP_ROOT_VALUE as an annotation on the root element instead using ObjectMapper

1条回答
  •  一向
    一向 (楼主)
    2021-02-07 23:24

    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 and @JsonTypeInfo together make it possible.

    Result:

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

    0 讨论(0)
提交回复
热议问题