相关疑难解决方法(0)

使用类名作为JSON Jackson序列化的根密钥

假设我有一个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的文档真的没有组织,而且大部分已经过时了.

java serialization json jackson

27
推荐指数
4
解决办法
6万
查看次数

如何禁用/启用jackson SerializationFeature.WRAP_ROOT_VALUE?

我正在使用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禁用该功能,这可能吗?

谢谢.

java android jackson retrofit

8
推荐指数
1
解决办法
3092
查看次数

标签 统计

jackson ×2

java ×2

android ×1

json ×1

retrofit ×1

serialization ×1