5

Is there an easy way to deserialize a JSON string to a domain class with support of embedded association; belongsTo and hasMany

{
  name: "Customer",
  contact: {
    name: "Contact"
  }
} 

class Customer {
  name 
  Contact contact
}

class Contact {
  String name
  static belongsTo = [customer:Customer]
}

in my controller I would like to do the following

def save() {
   def customer = new Customer(request.JSON)
   customer.save();
}

Now i'm forced to do

def save() {
   def contact = new Contact(request.JSON.contact);
   def customer = new Customer(request.JSON);
   customer.contact = contact;
   customer.save();
}
ken
  • 3,745
  • 6
  • 34
  • 49
  • grails.converters.json.default.deep is setted to true? –  Jan 16 '13 at 15:38
  • So to give you an idea, you have to convert that to : `{ name: "Customer", contact.name: "Contact" }` – James Kleeh Jan 16 '13 at 16:04
  • grails.converters.json.default.deep is not set at all, and doesn't make any difference when i set it to true in config.groovy – ken Jan 16 '13 at 16:07
  • @JamesKleeh Geee if that's true, then that's really counter-intuitive. It should rather be handled internally when parsing the JSON. – ken Jan 16 '13 at 16:09
  • Well the data binding is for setting data from an html form, not from a JSON, so it is not designed to take objects because it doesn't make any sense to do so on a form. – James Kleeh Jan 16 '13 at 17:16
  • data binding should be agnostic to the payload type. – ken Jan 16 '13 at 18:12
  • Out of curiosity, are you using Ember.js? – Zach Riggle Mar 17 '13 at 01:34

1 Answers1

0

Have you tried using JsonSlurper?

Example usage:

def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

Ref: http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html

you can try this

    Test test
    def result = new JsonSlurper().parseTest('yourString')
    test = result

Try this will work.

sanghavi7
  • 758
  • 1
  • 15
  • 38