Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool
Groovy JSON Handling in Gradle Scripts
If your project uses the Groovy DSL in build.gradle, you can handle JSON with Groovy's built-in groovy.json package. In practice that means importing JsonSlurper to read JSON and JsonOutput to write it, without adding a separate JSON dependency just for build script logic.
Quick Answer
- Yes. A Groovy DSL Gradle script can use Groovy's built-in JSON support directly.
- Add explicit imports such as
import groovy.json.JsonSlurperandimport groovy.json.JsonOutput. - To turn a map or
HashMapinto JSON, callJsonOutput.toJson(yourMap). - Keep JSON parsing inside a task action unless the JSON actually changes how the build is configured.
- Groovy DSL is still supported, but current Gradle guidance prefers Kotlin DSL for new builds.
What Gradle Gives You
In a Groovy-based Gradle build, the script already runs on Groovy, so basic JSON parsing and serialization do not require Jackson, Gson, or another library just to read a config file or emit a small JSON payload.
The important detail is that groovy.json classes are not part of Gradle's default script imports. The classes are available, but you should still import them explicitly at the top of the script.
import groovy.json.JsonOutput import groovy.json.JsonSlurper
Practical Gradle Examples
1. Convert a Map or HashMap to JSON
This is the direct answer for the common "map to JSON in Gradle Groovy DSL" use case. A Groovy map literal works, and a HashMap works too.
import groovy.json.JsonOutput
tasks.register("printPublishMetadata") {
doLast {
def payload = new HashMap<String, Object>()
payload.put("module", project.name)
payload.put("group", project.group.toString())
payload.put("version", project.version.toString())
payload.put("release", !project.version.toString().endsWith("-SNAPSHOT"))
def compactJson = JsonOutput.toJson(payload)
def prettyJson = JsonOutput.prettyPrint(compactJson)
println compactJson
println prettyJson
}
}JsonOutput.toJson() accepts maps, lists, strings, numbers, booleans, and nested combinations of those types. If you prefer Groovy's map literal syntax, this works the same way:
def payload = [
module : project.name,
version: project.version.toString(),
tags : ["gradle", "groovy", "json"]
]
println JsonOutput.toJson(payload)2. Parse JSON from a File Inside a Task
When JSON is only needed for a task's work, read it inside doLast. That keeps file I/O out of the configuration phase and plays better with Gradle's configuration cache.
import groovy.json.JsonSlurper
tasks.register("printReleaseConfig") {
doLast {
def configFile = layout.projectDirectory.file("config/release.json").asFile
if (!configFile.exists()) {
throw new GradleException("Missing config/release.json")
}
def config = new JsonSlurper().parse(configFile)
println "Channel: ${config.channel}"
println "Min SDK: ${config.android.minSdk}"
println "Enabled flags: ${config.flags.findAll { it.enabled }*.name}"
}
}JsonSlurper returns normal Groovy collections, so nested objects behave like maps and arrays behave like lists. Dot notation is convenient for simple access, but bracket notation also works when keys contain special characters.
3. Generate a JSON File as a Task Output
If another tool in your pipeline needs JSON, generate it from structured data instead of manually building a string.
import groovy.json.JsonOutput
tasks.register("generateBuildInfo") {
def outputFile = layout.buildDirectory.file("generated/build-info.json")
outputs.file(outputFile)
doLast {
def buildInfo = [
name : project.name,
version : project.version.toString(),
gradleVersion: gradle.gradleVersion,
javaVersion : System.getProperty("java.version"),
generatedAt : new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
]
def json = JsonOutput.prettyPrint(JsonOutput.toJson(buildInfo))
def target = outputFile.get().asFile
target.parentFile.mkdirs()
target.text = json
}
}Declaring outputs.file(...) gives Gradle the information it needs for up-to-date checks and incremental behavior.
4. Parse JSON During Configuration Only When It Shapes the Build
Top-level parsing is reasonable when the JSON decides which tasks or dependencies exist. If that data changes the build graph itself, reading it during configuration is appropriate.
import groovy.json.JsonSlurper
def featureFile = layout.projectDirectory.file("features.json").asFile
def features = featureFile.exists()
? new JsonSlurper().parse(featureFile)
: [enabled: []]
features.enabled.each { featureName ->
tasks.register("package${featureName.capitalize()}Assets") {
doLast {
println "Packaging assets for ${featureName}"
}
}
}Use this pattern sparingly. If JSON does not affect task creation, dependency selection, or plugin configuration, keeping the read inside a task action is usually the safer choice.
Current Tips and Caveats
- Import the JSON classes yourself:
JsonSlurperandJsonOutputare available in Groovy DSL builds, but they are not default Gradle script imports. - No extra dependency for normal Groovy DSL usage: if all you need is to parse a JSON file or turn a map into JSON inside
build.gradle, Groovy's built-in API is enough. - Prefer execution-time I/O: top-level file reads slow configuration and can reduce the value of configuration cache reuse.
- Use built-in serialization for maps and lists: avoid hand-written JSON strings unless you are emitting something trivial.
JsonOutput.toJson()is less error-prone. - Reach for stronger tooling only when needed: if your build logic needs schema validation, custom serializers, or large API payloads, move that work into a plugin,
buildSrc, or an included build and use a dedicated library there. - Kotlin DSL note: current Gradle documentation still supports Groovy DSL, but Kotlin DSL is the preferred option for new builds. These Groovy examples apply to
build.gradle, notbuild.gradle.kts.
Conclusion
For Groovy DSL Gradle scripts, the built-in answer is straightforward: import JsonSlurper to read JSON, import JsonOutput to write it, and serialize maps directly with JsonOutput.toJson(). That covers the most common Gradle JSON tasks cleanly without extra dependencies.
Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool