How to update gradle build resource files?

I have some JSON resource files in src/main/resources of the project. And those json files have some comments.
I wanted to strip out the JSON comments before package distribution during the gradle build.

I could strip out comments from src/main/resources files and package. But I don’t want to strip out comments from src/main/resources. I just wanted to remove the comments from json files during the gradle build so that only build/resources/main has json files with no comments.

Below code removes comments from src/main/resource (which I don’t want, just want json files with no comments in build/resources/main folder) and I tried with File("build/resources/main/${this.path}") but does not remove comments.

fileTree(file("src/main/resources/")).visit {
        val mapper = com.fasterxml.jackson.databind.ObjectMapper()
        mapper.enable(com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT)
        mapper.enable(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_COMMENTS)

        if (this.path.endsWith(".json")) {
            val r = mapper.writeValueAsString(mapper.readTree(File("src/main/resources/${this.path}").readText()))
            val myfile = File("src/main/resources/${this.path}")
//            val myfile = File("build/resources/main/${this.path}") tried but not removing comments
            myfile.writeText(r)
        }
    }

Any help or suggestions would be appreciated!

import org.apache.tools.ant.filters.StripJavaComments

tasks.processResources {
    filesMatching("*.json") {
        filter<StripJavaComments>()
    }
}
1 Like

Thanks Vampire for the solution.

It seems to work, but I do see the blank line after removing the comments.

Yes, it just removes the comments, which is from /* to */ and from // to end of line.

import org.apache.tools.ant.filters.StripJavaComments

tasks.processResources {
    filesMatching("*.json") {
        filter<StripJavaComments>()
        filter(object : Closure<String>(null, null) {
            fun doCall(line: String) = line.ifBlank { null }
        })
    }
}

It worked and very clean code. Thanks very much.

Ah, here a nicer version also circumventing the wrong null-ness annotation:

tasks.processResources {
    filesMatching("*.json") {
        filter<StripJavaComments>()
        filter { it.ifBlank { Supplier { null }.get() } }
    }
}
1 Like

Actually if you don’t mind the null being underlined in red in the IDE you can also just do

tasks.processResources {
    filesMatching("*.json") {
        filter<StripJavaComments>()
        filter { it.ifBlank { null } }
    }
}

I probably assumed it will not work as the IDE shows it in red, but it actually works just fine.

Agree, the null shows as red in IDE, but works.

Thanks a lot.