Grails将JSON解析为域类

时间:2013-12-16 04:17:02

标签: json grails grails-domain-class

嗨说我有一个域类

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

}

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

我发送了一个json对象。我可以执行new Book(Json)而不是手动设置属性吗?

2 个答案:

答案 0 :(得分:6)

使用内置Grails JSON转换器可以更轻松

import grails.converters.JSON

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

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

答案 1 :(得分:-1)

使用JsonBinder:

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

别忘了导入这些包:

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