【问题标题】:Grails parse JSON into domain classGrails 将 JSON 解析为域类
【发布时间】:2014-01-03 09:35:48
【问题描述】:

嗨,假设我有一个域类

class Book{
static hasOne=[author:Author]
long id
String name

}

class Author {
static hasMany=[books:Book]
long id
String name
}

我有一个 json 对象发送进来。我可以只做一个new Book(Json) 而不手动设置属性吗?

【问题讨论】:

  • 这样做会发生什么?
  • 你可能需要使用 new Book(JSON.parse(params)) 来为 GORM 获取正确的格式

标签: json grails grails-domain-class


【解决方案1】:

使用内置的Grails JSON 转换器使这更容易

import grails.converters.JSON

class BookController {
   def save = {
      def book = new Book(JSON.parse(yourJson))
      book.save(flush:true)
   }
}

在代码中发生了什么(我们正在解析 JSON 对象并在 Book 实体上设置属性并保存

【讨论】:

  • 当涉及数据类型时我遇到了这个问题......因为在 JSON 中它们显示为例如“2020-11-11”,我在域类中解析为空
  • 不错的答案,它会解析孩子并将它们放入实例中。
【解决方案2】:

使用 JsonBinder:

def json = request.JSON;
def book= new Book();
JsonBinder.bindJSON(book, json);

别忘了导入这些包:

import grails.converters.JSON;
import com.ocom.grails.JsonBinder;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多