首页 > 解决方案 > GROOVY 在文件夹中创建 JSON 文件时出现随机反斜杠

问题描述

我在编译 JSON 文件时遇到问题。这是我的方法(主要方法只有我正在编写此代码的方法的名称,所以我没有在此处包含主要方法。)

static void buildJSONFiles() {
        String commandJson = "C:/Users/Name/Desktop/docfiles/command_config.json"
        def data = [
                commands:
                        JsonOutput.toJson([new Commands(name:"upload", path:"\${BUILTIN_EXE(command)}", includeCommandName: true),
                                           new Commands(name:"file_info", path:"\${BUILTIN_EXE(command)}", includeCommandName: true)])
        ]

        println(data)

        def json_str = JsonOutput.toJson(data)
        def json_beauty = JsonOutput.prettyPrint(json_str)
        File file = new File(commandJson)
        file.write(json_beauty)
        println(json_str)

    }


    static class Commands {
        String name
        String path
        boolean includeCommandName
    }

我在控制台中的输出确实像这样

[commands:[{"includeCommandName":true,"path":"${BUILTIN_EXE(command)}","name":"upload"},{"includeCommandName":true,"path":"${BUILTIN_EXE(command)}","name":"file_info"}]]

但是将它发送到 JSON 文件,它会像这样

{"commands":"[{\"includeCommandName\":true,\"path\":\"${BUILTIN_EXE(command)}\",\"name\":\"upload\"},{\"includeCommandName\":true,\"path\":\"${BUILTIN_EXE(command)}\",\"name\":\"file_info\"}]"}

我知道 JSON 反斜杠是一个特殊字符,所以我希望它只会出现在:"${BUILTIN_EXE(command)}周围,但它会出现在我什至没有反斜杠的任何地方。

标签: javajsongroovy

解决方案


你没有“随机反斜杠”,你有双引号 JSON,因为你使用JsonOutput了两次。json_str一个包含 JSON 的字符串,然后您将其作为 JSON 值包装在更多 JSON 中。


推荐阅读