【问题标题】:gradle - Minimize json resources in processResourcesgradle - 最小化 processResources 中的 json 资源
【发布时间】:2016-12-07 21:51:21
【问题描述】:

我目前正在做一个项目。该项目的资源包含大量的 json 文件,这些文件最终都在最终的 jar 中。我已经在处理资源了。就像重命名文件和替换其他文件中的某些字符串一样。所以processResources 任务已经被使用了。

现在的问题是如何扩展它以使其最小化所有 json 文件。由于 Groovy 本身具有 json 实用程序,因此能够获取文件内容并在目标位置替换它们应该足以让一切正常工作。

这是我当前的processResources 任务:

processResources {
    // this will ensure that this task is redone when the versions change.
    inputs.property "version", project.version
    inputs.property "mcversion", project.minecraft.version

    // replace stuff in mcmod.info, nothing else
    from(sourceSets.main.resources.srcDirs) {
        include "mcmod.info"

        // replace version and mcversion
        expand "version": project.version, "mcversion": project.minecraft.version
    }

    // Minify json resources
    from(sourceSets.main.resources.srcDirs) {
        include "**/*.json"

        // Minify every file here
    }

    // copy everything else, thats not the mcmod.info
    from(sourceSets.main.resources.srcDirs) {
        exclude "mcmod.info"
        exclude "**/*.json"
    }

    rename "(.+_at.cfg)", 'META-INF/$1'

    from MainDirResources
}

最小化文件应该使用以下两行中的任何一行:

JsonOutput.toJson(new JsonSlurper().parseText( <file content here> ))
JsonOutput.toJson(new JsonSlurper().parse( <file here> ))

那么我要怎么做才能获取所有文件的内容或文件本身的所有实例并在输出目录中修改它们的内容呢?

【问题讨论】:

  • Gradle 可以运行一个可执行文件,你可以编写一个 shell 脚本来最小化 json 文件(删除新行),然后在你的 gradle 脚本中执行它。
  • @AlecZhang 我想尽可能避免使用 shell。同样正如我所说,最小化 JSON 本身不应该太难:groovy-lang.org/json.html
  • 你打算如何缩小它们?
  • @tim_yates JsonOutput.toJson(new JsonSlurper().parseText( &lt;file content here&gt; ))JsonOutput.toJson(new JsonSlurper().parse( &lt;file here&gt; ))

标签: java json gradle groovy


【解决方案1】:

以下方法可以解决问题:

processResources {
    // this will ensure that this task is redone when the versions change.
    inputs.property "version", project.version
    inputs.property "mcversion", project.minecraft.version

    // replace stuff in mcmod.info, nothing else
    from(sourceSets.main.resources.srcDirs) {
        include "mcmod.info"

        // replace version and mcversion
        expand "version": project.version, "mcversion": project.minecraft.version
    }

    // copy everything else, thats not the mcmod.info
    from(sourceSets.main.resources.srcDirs) {
        exclude "mcmod.info"
    }

    from MainDirResources

    rename "(.+_at.cfg)", 'META-INF/$1'

    // Minify json resources
    doLast {
        fileTree(dir: outputs.files.asPath, include: "**/*.json").each {
            File file -> file.text = JsonOutput.toJson(new JsonSlurper().parse(file))
        }
    }
}

由于outputs.files 仅包含一个目录(文件被复制到的目录),您可以将其转换为文件树并遍历文件并最小化 json 文件。应该作为processResources 中的最后一个操作运行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2016-02-15
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2017-09-07
    相关资源
    最近更新 更多