0

I am using restful service in grails. I have 2 classes Person

import grails.rest.Resource
@Resource(formats=['json', 'xml'])

class Person {
   String name 
   Address address 

    static constraints = {
             }
           }

and Address as

  import grails.rest.Resource
  @Resource(formats=['json', 'xml'])
  class Address {

    String house
    static constraints = {
    }
  } 

and in bootstrap I could create new person entry as follows

new Person(name:"John" , address: new Address(house:"John Villa").save()).save();

but the problem is I want to do the same thing using a POST request with JSON data. I set the UrlMappings.Groovy like

"/app/person"(resources: "person",  includes: ['index', 'show', 'save', 'update', 'delete', 'create', 'patch'])

"/app/address"(resources: "address",  includes: ['index', 'show', 'save', 'update', 'delete', 'create', 'patch'])

then I tried using POSTMAN rest client by sending a POST request to '/app/person' with JSON data

{
   "name":"john" ,
   "address": "{'house' :'sample address' }"
}

but it gives error 422 unprocessable entity.

How can I do the same using JSON ? I want to do both insertion and updation using POST and PUT methods.

  • could you show me source of your /app/person/index controller? – Michal_Szulc Jun 28 '15 at 10:31
  • I don't have a controller called PersonController. crud operations on Person objects are automatically set by grails when I use `"/app/person"(resources: "person")` this url mapping. –  Jun 28 '15 at 17:54

2 Answers2

0

The issue is with the JSON you are sending. While it's valid JSON it's not the correct representation for your resource. Your JSON should be:

{
   "name":"john",
   "address": 
   {
      "house":"sample address"
   }
}

As you can see from the above that the address property is actually a nested object and not a String like you are sending.

Joshua Moore
  • 24,706
  • 6
  • 50
  • 73
  • I tried with this format. but doesn't work. [this is thre response i'm getting](http://i.stack.imgur.com/HZ1tb.png). –  Jun 27 '15 at 18:12
0

Moreover did you check guides on http://grails.github.io/grails-doc/latest/guide/webServices.html ? Especially I would like you to check section:

grails.mime.types = [
    …
    json:          ['application/json', 'text/json'],
    …
    xml:           ['text/xml', 'application/xml']
]

Remember that when you process '/app/person' with PersonInstance, you in fact execute '/app/person/index/' with PersonInstance (so debug it's source if needed).

Also double check 'id' column in your classes.

Michal_Szulc
  • 4,097
  • 6
  • 32
  • 59