parse json with ant

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.

Tags:

Ant

Json