假设我有一个pojo:
import org.codehaus.jackson.map.*;
public class MyPojo {
int id;
public int getId()
{ return this.id; }
public void setId(int id)
{ this.id = id; }
public static void main(String[] args) throws Exception {
MyPojo mp = new MyPojo();
mp.setId(4);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
System.out.println(mapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.WRAP_ROOT_VALUE));
System.out.println(mapper.writeValueAsString(mp));
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用Jackson ObjectMapper进行序列化时,我得到了
true
{"id":4}
Run Code Online (Sandbox Code Playgroud)
但我想要
true
{"MyPojo":{"id":4}}
Run Code Online (Sandbox Code Playgroud)
我一直在搜索,Jacksons的文档真的没有组织,而且大部分已经过时了.
我正在使用JSONAPI,所以我需要包装一些类,但不是所有类,如:
{"users": {"aKey": "aValue"}} // wrapped.
{"aKey": "aValue"} // not wrapped.
Run Code Online (Sandbox Code Playgroud)
有一种方法可以动态地或从类本身禁用tis功能吗?
我试试这个:
包装/解包我正在这样做:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
JacksonConverterFactory jacksonConverterFactory = JacksonConverterFactory.create(objectMapper);
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new LoggingInterceptor());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(jacksonConverterFactory)
.build();
Run Code Online (Sandbox Code Playgroud)
我需要一些POJO禁用该功能,这可能吗?
谢谢.