我在Java和Play Framework中编写REST API,但是我遇到了Jackson序列化的问题。我有以下型号:
@Entity
@JsonRootName("country")
public class Country extends BaseModel<Country> {
private String name;
private Collection<City> cities;
...
}
Jackson对象映射器配置:
ObjectMapper mapper = Json.newDefaultMapper()
.configure(SerializationFeature.WRAP_ROOT_VALUE, true)
.configure(SerializationFeature.INDENT_OUTPUT, true);
然而,当我序列化国家模型时,
Country c = service.get(id);
return ok(toJson(c));
我得到以下输出:
{
"ObjectNode" : {
"country" : {
"id" : 5,
"name" : "Holandija",
"cities" : [ ]
}
}
}
预期输出为:
{
"country" : {
"id" : 5,
"name" : "Holandija",
"cities" : [ ]
}
}
杰克逊为什么要添加额外的ObjectNode节点?如何摆脱它?
答案 0 :(得分:1)
看来你在toJson方法中遇到了问题。以下代码完美(原始类Country为简单起见而修改):
@Entity
@JsonRootName(value = "country")
public class Country {
public int id;
public String name;
public Collection<String> cities;
public Country() {
}
public Country(int id, String name) {
this.id = id;
this.name = name;
}
}
测试:
@Test
public void testRootJsonMapping() throws JsonProcessingException {
Country tested = new Country(55, "Neverland");
ObjectMapper mapper = new ObjectMapper()
.configure(SerializationFeature.WRAP_ROOT_VALUE, true)
.configure(SerializationFeature.INDENT_OUTPUT, true);
String json = mapper.writeValueAsString(tested);
System.out.println("json:" + json);
}
测试输出:
json:{
"country" : {
"id" : 55,
"name" : "Neverland",
"cities" : null
}
}
如果使用Play API Json完成json转换,则应在启动时使用适当的映射选项进行配置:
private void configureJson() {
ObjectMapper mapper = new ObjectMapper()
.configure(SerializationFeature.WRAP_ROOT_VALUE, true)
.configure(SerializationFeature.INDENT_OUTPUT, true);
Json.setObjectMapper(mapper);
}
Here您可以在Play中阅读有关如何自定义Json转换的更多详细信息。