I have created SF to SF connection to put standard object cross org, getting error related to JSON response as 400 Bad Request. Error as: Unexpected parameter encountered during deserialization: LastName....' When im uncommenting line 'Commented 1' it works well with hardcoded values in JSON but fails when i put the field names it fails.

String endPoint='https:aaa//';                          
            Commented 1//String jsonstr='{"Lastname":"Testname123","Phone":"5565565","Website":"www.xyz.com","Status":"Open","Company":"1company"}';
           JSONGenerator gen = JSON.createGenerator(true);
            gen.writeStringField('LastName', Lastname);            
            gen.writeStringField('Phone', Phone);
            gen.writeStringField('Website', Website);
            gen.writeStringField('Status', status);
            gen.writeStringField('Company', company);
        // Get the JSON string.
            String jsonstr = gen.getAsString();
            String str1= jsonstr;
            system.debug(jsonstr); //this line displays proper JSON format(with the field values)
            Http h2= new Http();
            HttpRequest req2= new HttpRequest();             
            req2.setHeader('Content-Type','application/json; charset=utf-8');
            req2.setHeader('Authorization','Bearer ' + accessToken);          
            HttpResponse res2=h2.send(req2);

There are multiple ways to do this. The way that I follow is using a wrapper class

 public class RequestJSON{
    public String lastName;
    public String phone;
    public String website;
    public String status;
    public String company;

private String genpayload(String lastName, String phone, String website, String status, String company){
   RequestJSON rj = new RequestJSON();
   rj.lastName = lastName;
   rj.phone = phone;
   rj.website = website;
   rj.status = status;
   rj.company = company;

return JSON.serialize(rj);

You can then send the JSON in the request body.

  • You can improve the genpayload method by passing the sObject (Lead/Account/...) and using its field values inside the method, instead of passing so many paramters separately. – mritzi Aug 28 '20 at 13:58
  • Thanks It worked. – Priya Sep 3 '20 at 6:06

'Lastname' != 'LastName'. Map keys in Apex (and in most languages that might be processing the JSON that you send) are case-sensitive. Your generated JSON does not match the hard-coded JSON with respect to case.

As Avinash also pointed out, you should just be using serialization here; there is no reason to use the clumsy generator classes.

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.