使用类名作为JSON Jackson序列化的根密钥 [英] Use class name as root key for JSON Jackson serialization
本文介绍了使用类名作为JSON Jackson序列化的根密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个pojo:
Suppose I have a 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));
}
}
当我使用Jackson ObjectMapper进行序列化时,我得到了
When I serialize using the Jackson ObjectMapper, I just get
true
{"id":4}
但我想要
true
{"MyPojo":{"id":4}}
我到处搜索过,Jacksons的文档真的很棒没有组织,大多过时了。
I've searched all over, Jacksons documentation is really unorganized and mostly out of date.
推荐答案
通过在课程级别添加jackson注释 @JsonTypeInfo
,你可以有预期的输出。我刚刚在你的班级中添加了无变化。
By adding the jackson annotation @JsonTypeInfo
in class level you can have the expected output. i just added no-changes in your class.
package com.test.jackson;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
@JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME)
public class MyPojo {
// Remain same as you have
}
输出:
{
"MyPojo": {
"id": 4
}
}
这篇关于使用类名作为JSON Jackson序列化的根密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文