Pat*_*ick 9 java serialization json jackson
有没有办法SerializationFeature.WRAP_ROOT_VALUE在根元素上配置注释而不是使用ObjectMapper?
例如,我有:
@JsonRootName(value = "user")
public class UserWithRoot {
public int id;
public String name;
}
Run Code Online (Sandbox Code Playgroud)
使用ObjectMapper:
@Test
public void whenSerializingUsingJsonRootName_thenCorrect()
throws JsonProcessingException {
UserWithRoot user = new User(1, "John");
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
String result = mapper.writeValueAsString(user);
assertThat(result, containsString("John"));
assertThat(result, containsString("user"));
}
Run Code Online (Sandbox Code Playgroud)
结果:
{
"user":{
"id":1,
"name":"John"
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将此SerializationFeature作为注释而不是作为配置objectMapper?
使用依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
Isa*_*ank 21
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;
}
}
Run Code Online (Sandbox Code Playgroud)
@JsonTypeName并@JsonTypeInfo使它成为可能.
结果:
{
"user" : {
"id" : 1,
"name" : "John"
}
}
Run Code Online (Sandbox Code Playgroud)