我创建两个域,作者和书,作者有很多书,而书是属于作者。
class Author {
hasMany = [ books : Book ]
String name
}
class Book {
String title
Author author
}
BookController.groovy中的“savebook”功能
def savebook={
def json = request.JSON
def bookInstance = new Book()
bookInstance.properties = json
bookInstance.author_id = json.author_id
bookInstance.title = json.title
if (bookInstance.validate()) {
bookInstance.save();
def rep = [ respence: "1" ] // save
render rep as JSON
}
else {
def rep = [ respence: "0" ] // not save
render rep as JSON
}
}
我还没有找到该行的解决方案:“savebook”中的bookInstance.author_id = json.author_id
来创作作者的书。
我的第二个问题是如何使用JSON对象的结构来进行REST POST?
答案 0 :(得分:1)
对于问题的第一部分,您需要通过ID查看作者并将该实例分配给Book中的作者变量:
def author = Author.get(json.author_id)
bookInstance.author = author
bookInstance.title = json.title
author.addToBooks(bookInstance)
进入rest方法的JSON结构可以是任何有效的JSON。你可以简单地做
{
"author_id": 12345,
"title" : "See Jane Run"
}
或者你可以根据需要变得复杂。