IMRAN SHAIK
IMRAN SHAIK

Reputation: 635

How to read a json file into build.gradle and use the values the strings in build.gradle file

for example, read the json file in build.gradle and use the json values as strings in the file

{
  "type":"xyz",
  "properties": {
    "foo": {
      "type": "pqr"
     },
     "bar": {
       "type": "abc"
     },
     "baz": {
       "type": "lmo"
     }
  }
}

I need to call properties.bar.type and abc should be replaced there.

I need to convert these values to string and use in build.gradle file

Upvotes: 22

Views: 24927

Answers (2)

RenatoIvancic
RenatoIvancic

Reputation: 2092

As with Gradle 8.3 Kotlin is official DSL language, I'm extending the answer in case you are using buils.gradle.kts script file

Kotlin doesn't include JSON serialization component in the base language itself. You have to include dependency to kotlin-serialization-json. As you need this dependency in your script you have to include it through the buildscript{} block.

Solution that prints your value with Gradle logger:

import kotlinx.serialization.json.*
import java.nio.charset.Charset

plugins {
    id("base")
}
buildscript {
    dependencies {
        classpath("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
    }
}

tasks.register("readFromJson") {
    doLast {
        // Read json file
        val jsonFile = project.file("jsonFile.json")
        // Convert into immutable JSON object
        val fileAsJsonObject = Json.decodeFromString<JsonObject>(jsonFile.readText(Charset.defaultCharset())); 
        // Read properties.bar.type and print to Gradle logger
        logger.quiet("properties.bar.type value: " + fileAsJsonObject["properties"]?.jsonObject?.get("bar")?.jsonObject?.get("type"))
    }
}

Or you can mix and still use Groovy JsonSlurper class withing Kotlin DSL. While in Kotlin you have to expect the type of nodes in JSON.

import org.apache.groovy.json.internal.LazyMap

tasks.register("readFromJson") {
    doLast {
        // Read json file
        val jsonFile = project.file("jsonFile.json")
        // Convert into LazyMap at a root level
        val fileAsJsonObject =  groovy.json.JsonSlurper().parseText(jsonFile.readText()) as LazyMap
        logger.quiet("properties.bar.type value: S" +
                (((fileAsJsonObject["properties"] as LazyMap)["bar"] as LazyMap))["type"]
        )
    }
}

Upvotes: 1

Crazyjavahacking
Crazyjavahacking

Reputation: 9707

From Gradle you can execute any Groovy code and Groovy already has build-in JSON parsers.

E.g. you can use a task that will print your value into stdout:

task parseJson {
    doLast {
        def jsonFile = file('path/to/json')
        def parsedJson = new groovy.json.JsonSlurper().parseText(jsonFile.text)

        println parsedJson.properties.bar.type
    }
}

Upvotes: 41

Related Questions