如果这是重复的问题,请原谅我。我经历了一些要求类似的问题/答案,但同时又有点不知所措和困惑。我的要求是:
- 我得到一个JSON字符串/对象作为请求参数。 (例如:params.timesheetJSON)
- 然后我必须解析/迭代它。
这是我的grails控制器将接收的JSON:
{
"loginName":"user1",
"timesheetList":
[
{
"periodBegin":"2014/10/12",
"periodEnd":"2014/10/18",
"timesheetRows":[
{
"task":"Cleaning",
"description":"cleaning description",
"paycode":"payCode1"
},
{
"task":"painting",
"activityDescription":"painting description",
"paycode":"payCode2"
}
]
}
],
"overallStatus":"SUCCESS"
}
问题:
我如何从请求中检索整个JSON字符串? request.JSON在这里可以吗?如果是这样,request.JSON.timesheetJSON是否会向我产生我想要作为JSONObject的实际JSON?
解析从请求中获得的JSON对象的最佳方法是什么?是grails.converters.JSON吗?还是有其他简单的解析方法?就像某些API一样,它将通过自动处理解析来将JSON作为对象的集合返回。还是以编程方式仅通过JSON对象解析?
[就像我说的,如果问题听起来含糊,请原谅我。任何使用grails进行JSON解析的良好参考在这里也可能会有帮助。
Edit:现在获取JSON字符串的方式有所变化。我将JSON字符串作为请求参数。
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON) // No problem here. Returns a JSONObject. I checked the class type.
def jsonArray = jsonArray.timesheetList // No problem here. Returns a JSONArray. I checked the class type.
println "*** Size of jsonArray1: " + jsonArray1.size() // Returns size 1. It seemed fine as the above JSON string had only one timesheet in timesheetList
def object1 = jsonArray[1] // This throws the JSONException, JSONArray[1] not found. I tried jsonArray.getJSONObject(1) and that throws the same exception.
基本上,我现在想无缝遍历JSON字符串。