Force Jackson to add addional wrapping using annotations

前端 未结 7 977
渐次进展
渐次进展 2021-02-12 20:41

I have the following class:

public class Message {
    private String text;

    public String getText() {
        return text;
    }

    public void setText(St         


        
相关标签:
7条回答
  • 2021-02-12 21:22

    It was sad to learn that you must write custom serialization for the simple goal of wrapping a class with a labeled object. After playing around with writing a custom serializer, I concluded that the simplest solution is a generic wrapper. Here's perhaps a more simple implementation of your example above:

    public final class JsonObjectWrapper {
        private JsonObjectWrapper() {}
    
        public static <E> Map<String, E> withLabel(String label, E wrappedObject) {
            HashMap<String, E> map = new HashMap<String, E>();
            map.put(label, wrappedObject);
            return map;
        }
    }
    
    0 讨论(0)
  • 2021-02-12 21:29

    With Jackson 2.x use can use the following to enable wrapper without adding addition properties in the ObjectMapper

    import com.fasterxml.jackson.annotation.JsonTypeInfo;
    import com.fasterxml.jackson.annotation.JsonTypeName;
    
    @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
    @JsonTypeName(value = "student")
    public class Student {
      private String name;
      private String id;
    }
    
    0 讨论(0)
  • 2021-02-12 21:33

    Provided you don't mind the json having a capital m in message, then the simplest way to do this is to annotate your class with @JsonTypeInfo.

    You would add:

    @JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME)
    public class Message {
      // ...
    }
    

    to get {"Message":{"text":"Text"}}

    0 讨论(0)
  • 2021-02-12 21:36

    If using spring, then in application.properties file add following:-

    spring.jackson.serialization.WRAP_ROOT_VALUE=true

    And then use @JsonRootName annotation on any of your class that you wish to serialize. e.g.

    @JsonRootName("user")
    public class User {
        private String name;
        private Integer age;
    }
    
    0 讨论(0)
  • 2021-02-12 21:39

    I have created a small jackson module that contains a @JsonWrapped annotation, that solves the problem. See here for the code: https://github.com/mwerlitz/jackson-wrapped

    Your class would then look like:

    public class Message {
        @JsonWrapped("message")
        private String text;
    }
    
    0 讨论(0)
  • 2021-02-12 21:44

    A Simpler/Better way to do it:

    @JsonRootName(value = "message")
    public class Message { ...}
    

    then use
    new ObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true).writeValueAs...

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