Grails:无法解析 json,错误无方法签名:静态 grails.converters.JSON.parse()

Grails: Cannot parse json with error No signature of method: static grails.converters.JSON.parse()

我有一个 android 程序,它将使用 Grails 将 json 数据发送到服务器端。 当服务器端收到请求时,它应该解析json数据。

然而 Grails 总是显示如下错误:

No signature of method: static grails.converters.JSON.parse() is applicable for argument types: (org.codehaus.groovy.grails.web.json.JSONArray) values: [[[password:123, roleId:1, userName:abcde, userId:abc, email:c@a.com]]]

这里是Grails端的代码:

域class:

class User {

    String userId
    String userName
    String password
    String email
    int roleId

    static constraints = {
        userId size: 1..20, blank: false, nullable: false, unique: true
        userName size: 1..50, blank: false, nullable: false
        password size: 1..20, blank: false, nullable: false
        email size: 1..100, blank: true, nullable: true
        roleId blank: false, nullable: false
    }
}

控制器:

import grails.converters.JSON 
import org.codehaus.groovy.grails.web.json.JSONObject    

class userController {
        def index() {
            def requestJson = request.JSON
            def user = new User(JSON.parse(requestJson))

            //Save
            if (!user.save(failOnError: true)) {
                user.errors.each {
                println it
            }
        }
}

而且我想知道收到的 JSON 格式是否正确,因为它在错误日志中显示了三个 [[[ 和 ]]]。但是在 android 端,生成的 Json 应该如下所示:

[{"email":"c@a.com","password":"123","userName":"abcde","userId":"abc","roleId":1}]

客户端正在发送一个 JSON 数组。

[{"email":"c@a.com","password":"123","userName":"abcde","userId":"abc","roleId":1}]

当您从 request 访问负载时,它被解析为地图列表。所以 request.JSON 在这种情况下将是:

[
    [ 
      "email":"c@a.com",
      "password":"123",
      "userName":"abcde",
      "userId":"abc",
      "roleId":1
    ]
]

您必须在控制器中具有以下逻辑才能获得 Users 的列表:

def index() {
    def users = request.JSON.collect { new User( it ) }

    //Save
    if (!user*.save(failOnError: true)) {
        user*.errors.each {
            println it
        }
    }
}

这取决于您要如何保存,我想表明您必须处理用户列表而不是有效负载中的一个用户。