Custom Gradle The task of saving processed Json to a file. Android

I want to automate parsing and saving a json object for a resource or source directory during gradle build. I have a Jaw JsS class and I know how to run it from gradle. I do not know how to save the results or this class to any of the folders above. Below is an example of how I will run the script. Am I trying to do this in the 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'
+4
source share
2 answers

, JSON. JsonSlurper. . , . . ?

:

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
}

, .

+8

- , json pre-build . 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/

+8

Source: https://habr.com/ru/post/1535527/


All Articles