JSON对象,动态属性和序列化与Grails& MongoDB的

时间:2014-03-01 00:50:52

标签: mongodb grails jackson dynamic-properties

我正在尝试使用Grail的MongoDB插件将通用JSONObject保存到Domain对象。基本上它不适用于常规属性(这并不奇怪)。所以我添加了一个动态属性,它将JSONObject保存到数据库并将其拉回(yay)。但是,由于我已使用Jackson序列化程序替换了默认的JSON序列化程序(由于MongoDB插件和域对象的不良行为),因此动态属性未被序列化。

我可以使用什么API来获取添加到域的所有动态属性来序列化它? Object.properties()不返回它。我找不到任何其他方法来返回它。我现在必须修改杰克逊以序列化Grails对象。有什么想法可能最容易吗?

这是我的目标:

class ProblemAttempt {

   static final STEP_GUIDED = 'guided'
   static final STEP_INDEPENDENT = 'independent'

   static constraints = {
       timeSpent nullable: true
   }

   static mapWith="mongo"

   static mapping = {
       lessonAttemptId index: true
   }

   static embedded = ['tags']

   ObjectId id
   ObjectId problemId
   ObjectId userId
   String lessonExternalId
   ObjectId lessonAttemptId
   Date timeAnswered
   String stepName
   Boolean correct
   Integer timeSpent
   String lessonStatus
   List<String> tags

   ProblemAttempt(User user, String lessonExternalId, LessonAttempt attempt, String stepName, ObjectId problemId, boolean correct, Object answer) {

      this.userId = user.id
      this.lessonExternalId = lessonExternalId
      this.correct = correct
      this.lessonAttemptId = attempt.id
      this.lessonStatus = LearningStatus.INCOMPLETE
      this.problemId = problemId
      this.stepName = stepName
      this.timeAnswered = new Date()
      this['answer'] = answer  // have to use dynamic properties to persist generic JSON objects

      tags = []
      user.aspects.each {ProfileAspect aspect ->
          tags << aspect.class.simpleName
      }

      user.groups.each {DomainReference group ->
          tags << group.name
      }
  }

  public Object getUserAnswered() {
      return this['answer'] // this was added to handle serializing into json
  }

}

1 个答案:

答案 0 :(得分:0)

通常,Map或List类型的固定属性(取决于您的JSON的性质)应该没问题。只需确保保存java集合,而不是Jackson对象。后者不能被BSON序列化1到1