Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON to create an object in Groovy/Grails

I have a Groovy/Grails website that is being used to send data to Android clients via JSON. I have created both the Android client and the Groovy/Grails website; and they can output the same objects in JSON.

I can successfully create the respective objects in Android by mapping the JSON output to Java objects, however I was wondering if it's possible to use the JSON output to create a new domain object in Groovy/Grails? Is there a way of passing the JSON output to a controller action so that object will be created?

Here is an example of the JSON that I'd like to send;

{
    "class":"org.icc.callrz.BusinessCard.BusinessCard",
    "id":1,
    "businessCardDesigns":[],
    "emailAddrs":[
    {
        "class":"org.icc.callrz.BusinessCard.EmailAddress",
        "id":1,
        "address":"[email protected]",
        "businessCard":{
            "_ref":"../..",
            "class":"org.icc.callrz.BusinessCard.BusinessCard"
        },
        "index":0,
        "type":{
            "enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
            "name":"H"
        }
    },
    {
        "class":"org.icc.callrz.BusinessCard.EmailAddress",
        "id":2,
        "address":"[email protected]",
        "businessCard":{
            "_ref":"../..",
            "class":"org.icc.callrz.BusinessCard.BusinessCard"
        },
        "index":1,
        "type":{
            "enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
            "name":"W"
        }
    }
    ]
}

The "class" matches to the Domain I'd like to save to, the ID is the ID of the Domain, then each item within the businessCardDesigns and emailAddrs needs to be saved using similar methods (in the Domain the businessCardDesigns and emailAddrs are ArrayLists). Many thanks in advance!

SOLUTION:

@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody String json) {
    Owner.fromJsonToOwner(json).persist();
    return new ResponseEntity<String>(HttpStatus.CREATED);
}
like image 823
chrisburke.io Avatar asked Sep 09 '11 15:09

chrisburke.io


1 Answers

Using the built-in Grails JSON converter makes this easier than the other answers, in my opinion:

import grails.converters.JSON

class PersonController {
    def save = {
        def person = new Person(JSON.parse(params.person))
        person.save(flush:true)
    }
}

The other benefits are:

  • There's no need to muck around in any config files
  • The resulting JSON object can be manipulated, if necessary, before assigning properties
  • It's far clearer in the code what's happening (we're parsing a JSON object and setting the properties on the Person entity)
like image 177
OverZealous Avatar answered Sep 27 '22 01:09

OverZealous