2

Hi Say that I have a domain class

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

}

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

I have a json object sent in. Can I jus do a new Book(Json) and not manually set the property?

user903772
  • 1,554
  • 5
  • 32
  • 55

2 Answers2

8

Using the built-in Grails JSON converter makes this easier

import grails.converters.JSON

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

In the code what's happening (we're parsing a JSON object and setting the properties on the Book entity and saving

billjamesdev
  • 14,554
  • 6
  • 53
  • 76
Deepak
  • 2,287
  • 1
  • 23
  • 30
  • I have problems with this when Data types are involved ... since in the JSON they appear as e.g. "2020-11-11" and i get as null in the domain class aftar parsing – Rafael Dec 18 '14 at 11:37
  • 1
    Nice answer, it parses childs and put them in instances too. – IgniteCoders Nov 21 '18 at 13:51
-1

use the JsonBinder:

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

dont forget to import these packages:

import grails.converters.JSON;
import com.ocom.grails.JsonBinder;
user1577161
  • 165
  • 1
  • 4
  • 18