本文介绍了在写入File之前格式化JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在使用写入偏好数据等等文件主要是因为我希望高级用户能够修改/备份这些数据。杰克逊非常棒,因为它非常容易使用,并且显然表现得很好(参见),但我似乎遇到的唯一问题是当我运行 myObjectMapper.writeValue(myFile,myJsonObjectNode)时,它会写入所有数据在 ObjectNode 到一行。我想要做的是将JSON格式化为更友好的用户格式。

Currently I'm using the Jackson JSON Processor to write preference data and whatnot to files mainly because I want advanced users to be able to modify/backup this data. Jackson is awesome for this because its incredibly easy to use and, apparently performs decently (see here), however the only problem I seem to be having with it is when I run myObjectMapper.writeValue(myFile, myJsonObjectNode) it writes all of the data in the ObjectNode to one line. What I would like to do is to format the JSON into a more user friendly format.

例如,如果我将一个简单的json树传递给它,它将写入以下:

For example, if I pass a simple json tree to it, it will write the following:

{"testArray":[1,2,3,{"testObject":true}], "anotherObject":{"A":"b","C":"d"}, "string1":"i'm a string", "int1": 5092348315}

我希望它在文件中显示为:

I would want it to show up in the file as:

{
    "testArray": [
        1,
        2,
        3,
        {
            "testObject": true
        }
    ],
    "anotherObject": {
        "A": "b",
        "C": "d"
    },
    "string1": "i'm a string",
    "int1": 5092348315
}



Is anyone aware of a way I could do this with Jackson, or do I have to get the String of JSON from Jackson and use another third party lib to format it?

提前致谢!

推荐答案

尝试创建这样

 ObjectWriter writer = mapper.defaultPrettyPrintingWriter();

这篇关于在写入File之前格式化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:48
查看更多