sirFunkenstine
sirFunkenstine

Reputation: 8505

Custom Gradle Task to save parsed Json to file. Android

I want to automate the parsing and saving of a json object to asset or raw directory during gradle build. I have a java Json parsing class and I know how to run it from gradle. What i do not know is how to save the results or that class to either of the above folders. Below is an example of how i will be running the script. Is what i am trying to do possible in its current state??

package com.mrhaki.java;

   public class SimpleParser {
       public static void main(String[] args) {
         //parse content
       }
   }

Gradle Build

apply plugin: 'java'

task(runSimpleParser, dependsOn: 'classes', type: JavaExec) {
    main = 'com.mrhaki.java.SimpleParser'
    classpath = sourceSets.main.runtimeClasspath
    args 'mrhaki'
    systemProperty 'simpleparser.message', 'Hello '

}
defaultTasks 'runSimpleParser'

Upvotes: 8

Views: 25164

Answers (2)

Steven Veltema
Steven Veltema

Reputation: 2150

Just for a slightly more detailed answer, I had to do something similar recently, iterating over a simple json file and generating a strings.xml pre-build. The relevant bit from build.gradle:

import groovy.json.JsonSlurper

task generateStrings {
    def inputFile = new File("app/src/main/assets/localized_strings.json")
    def json = new JsonSlurper().parseText(inputFile.text)

    def sw = new StringWriter()
    def xml = new groovy.xml.MarkupBuilder(sw)

    //add json values to the xml builder
    xml.resources() {
        json.each {
            k, v ->
                string(name: "${k}", "${v}")
        }
    }

    def stringsFile = new File("app/src/main/res/values/strings.xml")
    stringsFile.write(sw.toString())
}


gradle.projectsEvaluated {
    preBuild.dependsOn('generateStrings')
}

http://www.veltema.jp/2014/08/27/generating-strings.xml-from-JSON-at-Build-in-Android-Studio/

Upvotes: 10

Opal
Opal

Reputation: 84854

I thinks that there's no need to use external JSON parser. Instead use JsonSlurper. Works really well. In the task above, create a file, write the parsed content there and save it in the declared folder. That's all. What exactly You don't know?

It will be similar to:

task json() << {
   def f1 = new File('path/to/file1')
   def f2 = new File('path/to/file2')
   f1.text //= set content here
   f2.text //= set content here
}

That's all as far as I understood.

Upvotes: 10

Related Questions