0

I am using JSON.Serialize to generate JSON from Apex class object then sending JSON request to Ruby on RAILS but I'm getting invalid JSON format because SALESFORCE is sending JSON with escape character format.

{“{\”enpoint\”:\”\”,\”addresss\”:\”bangalore\”,\”id\”:\”12345\”}"} 

Please note, I am using JSON.serialize(obj) to generate the JSON string.

["{\"Status\":\"Json format is invalid. Please check JSON format\"}"] 
6
  • You are probably serializing an already serialized Json, are you sure obj, isn't already a Json String? Did you output it in apex? what did you see?
    – itsmebasti
    Commented Oct 14, 2017 at 2:16
  • I'm using below line of code to generate JSON string- JSONGenerator gen=JSON.createGenerator(true); return Json.serialize(root) ; Here, root is the object of class.
    – Ramesh
    Commented Oct 14, 2017 at 2:23
  • I'm using below line of code to generate JSON string- JSONGenerator gen=JSON.createGenerator(true); return Json.serialize(root) ; Here, root is the object of class.
    – Ramesh
    Commented Oct 14, 2017 at 2:26
  • Please add this code to your question, so we can understand what you are doing. When you are Using the gereator you won't need serialize, you just return it with gen.getAsString(); <- this is already a Json
    – itsmebasti
    Commented Oct 14, 2017 at 2:30
  • Thanks Basti. I don't think we can pass object name in gen.genAsString() method. Also, when we create gen object on JSON then also could not pass object name here. Sorry, I am asking too many thing but I'm very new in Salesforce. ( JSONGenerator gen=JSON.createGenerator(true))
    – Ramesh
    Commented Oct 14, 2017 at 2:49

1 Answer 1

1

With your given object structure you won't need the JSON generator, just use serialize:

RootObject root=new RootObject();
root.activity=new Activity();

Example objBody=new Example();
objBody.id='S001';
objBody.cookie_id='';
objBody.name='Ramesh';
objBody.source='Mail';

root.activity=objBody;

return JSON.serialize(root);

Please add the code from the comments to your Question (click "edit" on the question)

2
  • Thanks Basti. I copy your code in my Apex class but still Salesforce is sending JSON request with escape characters to Ruby On Rails API.
    – Ramesh
    Commented Oct 14, 2017 at 3:23
  • We are sending JSON request to Rails API which is calling from Salesforce. API is failing because of invalid JSON structure.I tried all Salesforce provide JSON method but still RAILS API is receiving JSON with escape character format.
    – Ramesh
    Commented Oct 14, 2017 at 13:10

You must log in to answer this question.

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