2

I am exploring a way to pass a sobject to an apex class. Below is my apex class:

@RestResource(urlMapping = '/resturl/*')
global with sharing class check {
    public boolean Hide {
        get;
        set;
    }
    public check(sobject__c customobject) {
        Hide = false;
        customobject.field1__c = false;
    }

    @HttpPost
    global static Boolean save(sobject__c customobject) {
        check objectcheck = new check(customobject);
        return objectcheck.saves();
    }

    private saves() {

        try {
            // do some stuff
        } catch (Exception ex) {
            return false;
        }
        return true;

    }
}

I am calling this rest method save() using a JSON request formed in workbench, which looks like this:

{
  "customobject" : {
  "field1__c" : "true"
  }
}

Is this the right way to pass a custom Sobject in JSON with a custom field named field1__c?

In response of calling the method from workbench I do get a 200 HTTP response code, but I do get a false returned instead of true. So before I go into debugging I just want to make sure if I am passing the Sobject correctly in JSON.

1 Answer 1

1

Try this format:

{
    "attributes": {
        "type": "customobject__c"
    },
    "field1__c": true
}

This is assuming that you are writing to a proper boolean object. This should work because it's a serialized output from one of my own custom objects.

To get the JSON data, you should get it from the rest body, ie:

@HttpPost
global static String save(){
    String body = System.RestContext.request.requestBody.toString();
    customobject__c obj = (customobject__c)JSON.deserialize(body,customobject__c.class); 
}

For more info, go here Also thanks to this post for helping me correct a problem with my original answer.

1
  • I believe I am passing the JSON correctly. In my try block where I have //do stuff I was using an object which I get from a standard controller. Since there is not VF page in rest calls it was throwing an error. Now when I removed that object things worked. But thanks for your input this is a different way of passing a JSON from mine.
    – SfdcBat
    Jun 23, 2016 at 17:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .