Reputation: 2483
I am looking for a way to parse a string into json array, so that I can iterate the same and access the objects inside it. I have been looking around for some time but no help.
I found one way which is
#set ($myjson = $json.fetch('http://www.url.org/feeds/json-packages.dot'))
but I want to parse one local string variable into json array. How can we do that?
Upvotes: 1
Views: 3929
Reputation: 801
You could use a library like this, and put in your velocity context a "JSONUtils" object. This object would expose a method "jsonArrayFromString", whose implementation would be as simple as
public JSONArray jsonArrayFromString(String jsonString) {
try {
return new JSONArray(jsonString);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
Here is the documentation of the JSONArray class. Then you can use this object in your template like this:
#set ($myjson = $JSONUtils.jsonArrayFromString($myString))
#set ($length = $myjson.length())
#foreach( $i in [0..$length-1] )
## Use one of the getter methods for the object in this index.
#end
Of course you could also put a similar method that creates a JSONObject from a string.
Upvotes: 1