【发布时间】:2014-03-18 00:50:14
【问题描述】:
如果这是一个重复的问题,请原谅我。我已经完成了一些具有类似要求的问题/答案,但同时不知何故有点不知所措和困惑。我的要求是:
- 我得到一个 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 的任何好的参考在这里也可能会有所帮助。
编辑:我现在获取 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 字符串。
【问题讨论】:
-
JSON 被视为 Map。因此,在您的情况下,您可以使用 map.key 从 json 中获取值,例如:json.loginName
-
谢谢柏。但我的问题更多是关于“技术”或“工具”或“api”,这将使通过 JSON 解析生活变得更容易。
标签: json grails grails-plugin