简体   繁体   English

JSON漂亮打印自定义

[英]JSON pretty print customization

I'm writing a tool to modify huge json file in groovy. 我正在编写一个工具来修改Groovy中的巨大json文件。 I read this file, add new entry and save, but I'would like to avoid changes in places I didn't touch. 我阅读了此文件,添加了新条目并保存,但是我想避免我没有碰过的地方发生变化。

I'm using new JsonBuilder( o ).toPrettyString() to get pretty formatted json output, but this function gives me result like this: 我正在使用new JsonBuilder( o ).toPrettyString()来获取漂亮的json输出,但是此函数给我这样的结果:

{
    "key": "Foo",
    "items": [
        {
            "Bar1": 1
        },
        {
            "Bar2": 2
        }
    ]   
}

when I need to get this: 当我需要得到这个时:

{
    "key": "Foo",
    "items": 
    [
        {
            "Bar1": 1
        },
        {
            "Bar2": 2
        }
    ]   
} 

There should be newline before [ . [之前应有换行符。

It's important to me, because in other way I cannot find in GIT history, what I really changed. 这对我很重要,因为以其他方式我无法在GIT历史中找到真正改变的地方。

Do you have any idea how to achieve this? 你有什么想法要实现吗?

The JsonBuilder method toPrettyString() delegates directly to JsonOutput.prettyPrint() as follows: JsonBuilder方法toPrettyString()直接委托给JsonOutput.prettyPrint() ,如下所示:

public String toPrettyString() {
    return JsonOutput.prettyPrint(toString());
}

The latter method is not really customizable at all. 后一种方法根本不是真正可定制的。 However, the source is freely available from any Maven central repository or mirror. 但是,可以从任何Maven中央存储库或镜像免费获得该源。 I would suggest finding the source and creating your own variant of the method that behaves the way you would like it to. 我建议您找到源并创建自己的方法变体,使其行为符合您的期望。 The source for JsonOutput.prettyPrint() is only about 65 lines long and shouldn't be that hard to change. JsonOutput.prettyPrint()的源只有大约65行,并且应该不难更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM