I am looking for a way to do something like this without being forced to have to create a new separate object for the "content" value which would just hold a string inside the object.
@JsonNestedProperty("value.content")
String value = "my_value";
{
"value": {
"content": "my_value"
}
}
Currently making new objects in order to nest fields
@JsonProperty("value")
MyContent value;
class MyContent {
@JsonProperty("content")
String content = "my_value";
}
You can use the ObjectWriter#withRootName
method to wrap a distinct Content
object with a string as a new rootname in the serialization process like the example below:
public class Content {
@JsonProperty("content")
String content = "my_value";
}
Content content = new Content();
//wrapping the Content obj with new rootname "value"
//it prints {"value":{"content":"my_value"}}
System.out.println(mapper.writer()
.withRootName("value")
.writeValueAsString(content));
If you want to wrap all Content
objects with the same rootname you can annotate the Content
class with the JsonRootName
annotation and use the ObjectWriter#with
method with the SerializationFeature#WRAP_ROOT_VALUE
serialization feature like the example below:
@JsonRootName(value = "value")
public class Content {
@JsonProperty("content")
String content = "my_value";
}
Content content = new Content();
//it prints {"value":{"content":"my_value"}}
System.out.println(mapper.writer()
.with(SerializationFeature.WRAP_ROOT_VALUE)
.writeValueAsString(content));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.