2017-06-06 42 views
0

我正在寻找一种将字符串解析为json数组的方法,以便我可以迭代它并访问其中的对象。我一直在四处寻找,但没有任何帮助。在速度模板中将字符串解析为JSONArray

我发现这是

#set ($myjson = $json.fetch('http://www.url.org/feeds/json-packages.dot')) 

的一种方式,但我想分析一个本地字符串变量成JSON数组。我们怎么做到这一点?

回答

1

您可以使用类似this的库,并将速度上下文中放入一个“JSONUtils”对象。这个对象将暴露的方法“jsonArrayFromString”,其实施是简单的

public JSONArray jsonArrayFromString(String jsonString) { 
    try { 
     return new JSONArray(jsonString); 
    } catch (JSONException e) { 
     throw new RuntimeException(e); 
    } 
} 

这里是JSONArray类的文档。然后你就可以在你的模板中使用这个对象是这样的:

#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 

当然,你也可以把从一个字符串创建一个JSONObject类似的方法。