Java:Jackson缩进添加了新的地图标签

时间:2019-06-20 10:06:08

标签: java json indentation jackson-databind

我正在使用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很好,但是没有缩进。你知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

Jackson对0.101.1的任何知识都不是来自另一个库。因此,它正在像其他任何类一样编写其内部结构。使用https://github.com/FasterXML/jackson-datatype-json-org告诉杰克逊如何对待它:

JSONObject

或者使用杰克逊自己的JsonNode(有关说明,请参见Working with Tree Model Nodes in Jackson)。