Grails mongodb map类型给出了illegalStateException

时间:2014-03-22 17:23:35

标签: java mongodb grails gorm

我正在尝试将Map属性添加到用户域

class User {
    String id
    String username
    String password
    ....
    Map<String, Follower> followers
    //i've tried also without embeded and got the same error. also tried follower insead of followers
    static embedded = ['followers']
}

class Follower {
    String name
    List<String> interests
}

我有一个安静的控制器实现了保存方法

@Transactional
@Secured(['permitAll'])
def save(User user){
    user.id = new ObjectId().encodeAsBase64()
    user = user.insert(flush: true)
    respond 
}

可悲的是,我得到了一个例外:

java.lang.IllegalStateException: Cannot convert value of type [com.google.gson.JsonObject] to required type [Follower] for property 'followers[532dbe3b8fef86ebe3e64789]': no matching editors or conversion strategy found Around line 26 ofUserController.groovy

第26行是:user = user.insert(flush:true)

示例json请求:

{
    username : "roy",
    password : "123456",

    followers : {
        "532dbe3b8fef86ebe3e64789" : {
            name : "Roy",
            interests : ["math"]
        }
    }
}

非常感谢任何帮助

谢谢!

罗伊

1 个答案:

答案 0 :(得分:1)

您正在尝试将JSONObject保存为Follower实例。解决问题的直接方法是手动将它们转换为Follower实例:

def save(User user){
  user.id = new ObjectId().encodeAsBase64()
  user.followers = user.followers.collect{ new Follower( it ) }
  user = user.insert(flush: true)
  respond 
}

如果你有更多这种情况,你应该注册一个属性编辑器进行转换JSON&lt; - &gt;从动