parse json with ant
I hav开发者_如何学Goe an ant build script that needs to pull files down from a web server. I can use the "get" task to pull these files down one by one. However, I'd like to be able to get a list of these files first and then iterate over the list with "get" to download the files. The webserver will report the list of files in json format, but I'm not sure how to parse json with ant.
Are there any ant plugins that allow for json parsing?
I used Dave's suggestion above and it worked out pretty well. Here's what I came up with:
(Note, I ripped this out of my actual build file and tried to remove anything specific and just leave the example parts, so forgive me if it's missing anything or whatever, but it should give you an idea of how this works).
<?xml version="1.0"?>
<project name="jsonExample" default="all">
<target name="all" depends="example" />
<target name="example">
<!-- This uses Rhino - an Open Source implementation of JavaScript written in Java -
to parse JSON. -->
<script language="javascript"> <![CDATA[
importClass(java.io.File);
importClass(java.io.FileReader);
importClass(java.io.BufferedReader);
importClass(java.io.FileWriter);
importClass(java.io.BufferedWriter);
var file = new File("/path/to/myJSON.js");
fr = new FileReader(file);
br = new BufferedReader(fr);
// Read the file we just retrieved from the webservice that contains JSON.
var json = br.readLine();
// Evaluate the serialized JSON
var struct = eval("(" + json + ")");
// Get the data from
var value = struct.data.VALUE;
echo = example.createTask("echo");
echo.setMessage("Value = " + value);
echo.perform();
]]>
</script>
</target>
You can use a <script> task to run JavaScript to decode your JSON.
Here is the macro I use to load json-properties.
<macrodef name="json-properties">
<attribute name="jsonFile"/>
<sequential>
<local name="_jsonFile"/>
<property name="_jsonFile" value="@{jsonFile}"/>
<script language="javascript">//<![CDATA[
var json = new Packages.java.lang.String(
Packages.java.nio.file.Files.readAllBytes(
Packages.java.nio.file.Paths.get(project.getProperty("_jsonFile"))), "UTF-8");
var properties = JSON.parse(json);
for(key in properties) {
project.setProperty(key, properties[key]);
}
//]]></script>
</sequential>
</macrodef>
精彩评论