Android 自定义 Gradle 任务将解析的 Json 保存到文件。安卓
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22934371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom Gradle Task to save parsed Json to file. Android
提问by sirFunkenstine
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??
我想在 gradle 构建期间自动解析 json 对象并将其保存到资产或原始目录。我有一个 java Json 解析类,我知道如何从 gradle 运行它。我不知道如何将结果或该类保存到上述任一文件夹中。下面是我将如何运行脚本的示例。在目前的状态下,我正在尝试做的事情可能吗?
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'
回答by Opal
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?
我认为没有必要使用外部 JSON 解析器。而是使用JsonSlurper
. 效果很好。在上面的任务中,创建一个文件,在那里写入解析的内容并将其保存在声明的文件夹中。就这样。你不知道的究竟是什么?
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.
据我所知,这就是全部。
回答by Steven Veltema
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:
只是为了更详细的答案,我最近不得不做一些类似的事情,迭代一个简单的 json 文件并生成一个 strings.xml 预构建。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/
http://www.veltema.jp/2014/08/27/generating-strings.xml-from-JSON-at-Build-in-Android-Studio/