我有嵌套对象,当我使用jackson将它序列化为json时,我希望获得根名称。这是我想要的结果(我向所有花爱好者道歉,但只是需要一个例子,这不能被解释为准确的数据):
{
"plants": "flowers",
"types": {
"rose" : {
"color": "red",
"height": 25,
}
}
}
我有两个类,一个包装类:
public class JsonWrapper {
public String plants = "flowers";
public Object types;
}
和"花"类:
@JsonRootName("rose")
public class rose{
public String color = "red";
public int height = 25;
}
现在我做的是:
JsonWrapper wrapper = new JsonWrapper();
wrapper.types = new rose();
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
String jsonInString = mapper.writeValueAsString(wrapper);
我得到的结果是:
{
"JsonWrapper":{
"plants": "flowers",
"types": {
"color": "red",
"height": 25,
}
}
}
因此,我获取了未注释的包装器对象的根名称,但未获取注释的子对象的根名称。有没有办法告诉杰克逊没有得到根名称没有,并分析子对象?
答案 0 :(得分:1)
没有JsonRootName
的备用解决方案。
JsonWrapper.java
import java.util.HashMap;
import java.util.Map;
public class JsonWrapper {
public String plants = "flowers";
Map<String, Flower> types = new HashMap<>();
public Map<String, Flower> getTypes() {
return types;
}
public void setTypes(Map<String, Flower> types) {
this.types = types;
}
}
Flower.java
public class Flower {
public String color = "red";
public int height = 25;
}
Main.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
JsonWrapper wrapper = new JsonWrapper();
wrapper.getTypes().put("rose", new Flower());
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(wrapper);
System.out.println(jsonInString);
}
}