如果我无法使用注解 JsonTypeInfo 标记 class,如何为 class 自定义 json 包装键?

How to customize json wrapped key for class if I am not able to mark that class with annotation JsonTypeInfo?

我有这样的代码:

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.writeValueAsString(mp));
    }
}

预期有效:

{"MyPojo":{"id":4}}

但是我想自定义那个名字。我无法用 @JsonTypeInfo 标记 MyPojo 因为我从图书馆拿了这个 class。

jackson有办法吗?

您可以像这样创建一个新的 class,而不是使用 SerializationConfig.Feature.WRAP_ROOT_VALUE

public class MyWrapper {

    private MyPojo myName = new MyPojo();

    public void setId(int id) { myName.setId(id); }
}

如果您从这种类型的对象创建 JSON,该属性的名称将是 myName,例如:{"myName" : {"id" : 4} }.

您也可以专门为此使用 ObjectWriter class:

MyPojo mp = new MyPojo();
mp.setId(4);
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer().withRootName("TestPojo");
System.out.println(writer.writeValueAsString(mp));