0

I am trying to create a rest endpoint. My JSON Body:-

{
  "Name":"First Widget"
} 

Apex Class:-

@RestResource(urlMapping='/Widgets/*')
global class WidgetController {

    @HttpPost 
    global static String createNewWidget(String Name) {
        Widget__c w = new Widget__c();
        w.Name = Name;
        insert w;

        return 'Done';
   }

when i try to test this , its working fine. But When i add another fields like,

JSON:-

{
"Name":"First Widget",
"Email__c": "geru9@GMAIL.COM"
}

Apex Class:-

@RestResource(urlMapping='/Widgets/*')
global class WidgetController {

    @HttpPost 
    global static String createNewWidget(String Name,string email) {
        Widget__c w = new Widget__c();
        w.Name = Name;
        w.Email__c = email;
        insert w;

        return 'Done';
   }

ITS THROWING ERROR LIKE:-

Unexpected parameter encountered during deserialization: Any

Help would be appreciated!

0

If your signature for the rest post is like this:

global static String createNewWidget(String Name,string email)

Then the JSON has to match exactly the variable names

{
 "Name":"First Widget",
 "email": "geru9@GMAIL.COM"
}

Salesforce automatically deserializes the incoming JSON object into the arguments of your POST signature. Any additional arguments supplied in the POST JSON body will throw an exception.

To avoid this, don't use any arguments in your POST method signature:

...
private class WidgetRequest { // inner class
    String Name;
    String email;
}

@HttpPost 
global static String createNewWidget() {
    RestRequest     restRqst = RestContext.request;
    WidgetRequest = (WidgetRequest) 
      Json.deserialize(restRqst.requestBody.toString(),WidgetRequest.class);

}

Now, if the incoming request looks like this:

{
 "Name":"First Widget",
 "fooemail": "geru9@GMAIL.COM",
 "bar" : "somebar"
}

the property fooemail is ignored and will be null in your apex. Same for bar

|improve this answer|||||
  • @veeran by forum convention; if the answer solved your issue, you should mark as 'Answered' so others in the community can benefit. – cropredy Nov 28 '17 at 15:16
  • i ticked that as green. hope this would be fine. – veeran Nov 29 '17 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.