I have the following class:
public class Message {
private String text;
public String getText() {
return text;
}
public void setText(St
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;
}
}
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;
}
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"}}
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;
}
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;
}
A Simpler/Better way to do it:
@JsonRootName(value = "message")
public class Message { ...}
then use
new ObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true).writeValueAs...