@Json Annotation
The @Json annotation is used to override the behavior of JsonSerializer on individual bean classes or properties.
The annotation can be applied to beans as well as other objects serialized to other types (e.g. strings).
When to use it
Use @Json(wrapperAttr) when a bean must appear inside a JSON object under a fixed attribute name, for example when a consumer expects {"personBean":{...}} rather than the bare bean.
It applies wherever the class is serialized, so you don't wrap the value by hand at each call site.
Example
import org.apache.juneau.marshall.json.*;
public class JsonAnnotationExample {
@Json(wrapperAttr="personBean")
public static class Person {
public String name = "John Smith";
}
public static void main(String[] args) throws Exception {
System.out.println(JsonSerializer.DEFAULT.write(new Person()));
}
}
The program prints {"personBean":{"name":"John Smith"}}.
The following shows the JSON representation with and without the annotation present:
| Without annotation | With annotation |
|---|---|
| |
Options
| Element | Effect |
|---|---|
| wrapperAttr | Wrap the bean inside a JSON object with this attribute name. Empty (the default) means no wrapping. |