我有这样的代码:
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}}
但我想自定义该名称。我无法用
MyPojo
标记@JsonTypeInfo
,因为我从图书馆学习此课程。有没有办法在杰克逊做到这一点?
最佳答案
您也可以专门为此类使用ObjectWriter
:
MyPojo mp = new MyPojo();
mp.setId(4);
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer().withRootName("TestPojo");
System.out.println(writer.writeValueAsString(mp));