我正在使用jackson 2.9.8
,并且试图美化我的json。
我正在使用的代码是:
protected void setSuccessMessage(HttpServletResponse response, JSONObject jObj) throws IOException {
// Set the status
response.setStatus(200);
// Create the response
response.setContentType("application/json");
PrintWriter out = response.getWriter();
jObj.put("success", 1);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
out.print(mapper.writeValueAsString(jObj));
out.close();
}
但是,我的输出中有一个我不需要的新map
标记。输出为:
{
"map" : {
"success" : 1,
"documents_metata" : {
"myArrayList" : [ {
"map" : {
"documentType" : "PS_XML",
"patientId" : "x",
"effectiveTime" : "2019-05-08",
"author" : "xxx",
"repositoryId" : "xxx",
"id" : "xxx",
"title" : "xxx"
}
}, {
"map" : {
"documentType" : "PS_PDF",
"patientId" : "x",
"effectiveTime" : "2019-05-08",
"author" : "xxx",
"repositoryId" : "xxx",
"id" : "xxx",
"title" : "xxx"
}
} ]
}
}
}
正确的应该是:
{
"success": 1,
"documents_metadata": [
[
{
"documentType": "PS_PDF",
"patientId": "x",
"effectiveTime": "2019-05-08",
"author": "xxx",
"repositoryId": "xxx",
"id": "xxx",
"title": "xxx"
},
{
"documentType": "PS_XML",
"patientId": "x",
"effectiveTime": "2019-05-08",
"author": "xxx",
"repositoryId": "xxx",
"id": "xxx",
"title": "xxx"
}
]
]
}
不带jackson
的json很好,但是没有缩进。你知道如何解决这个问题吗?
答案 0 :(得分:1)
Jackson对0.101.1
的任何知识都不是来自另一个库。因此,它正在像其他任何类一样编写其内部结构。使用https://github.com/FasterXML/jackson-datatype-json-org告诉杰克逊如何对待它:
JSONObject
或者使用杰克逊自己的JsonNode
(有关说明,请参见Working with Tree Model Nodes in Jackson)。