java - Grails mongodb 映射类型给出非法状态异常

标签 java mongodb grails grails-orm

我正在尝试将 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
}

我有一个实现保存方法的 Restful Controller

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

遗憾的是我遇到了一个异常(exception):

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"]
        }
    }
}

任何帮助将不胜感激

谢谢!

罗伊

最佳答案

您正在尝试将 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 <-> Follower

关于java - Grails mongodb 映射类型给出非法状态异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22580980/

相关文章:

java - 为什么私有(private)构造函数禁止继承?

.net - 无法将类型为 'MongoDB.Bson.BsonDocument' 的对象转换为类型 'MongoDB.Bson.BsonBinaryData'

node.js - 在引用文档中插入数据?

grails - 如何在Grails Controller 中调用方法而不渲染新 View ?

ajax - Grails Spring Security向 Controller Action 提出Ajax请求时收到403错误

ajax - Twitter Bootstrap 模式调用 Controller 操作

java.io.IOException : ipm. 注意。该系统找不到指定的文件

java - 在单元测试中模拟/ stub RuntimeException

javascript - Mongoose 聚合成一个嵌套的 doc 获取计数并将新值附加到查询结果

java - 获取当前版本号 `tzdata`