Search code examples
javascriptjsonserializationodata

Posting data using javascript with ODATA format


I'm facing an issue when converting ODATA string into JSON while posting on my Dynamics CRM. When I'm trying to serialize that way:

var phoneCallAssociationJsonData = '{'
               +'"@odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls('+ phoneCallUid +')"'
               +'}';

And serialize it in the request like that: JSON.stringify(phoneCallAssociationJsonData);

I get a BAD REQUEST response. But When I use POSTMAN to post data and I copy the following JSON:

{"@odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls(12a59ec0-76b5-e611-80ed-5065f38a8ad1)"}

It works perfectly. Does someone know if there is a special way way to serialize string with odata format ?

I've tried to create a javascript object but adding a [email protected] is not possible because @ is not an allowed character.


Solution

  • Firstly, rather than creating a string, which you then stringify, create an OBJECT

    var phoneCallAssociationJsonData = {
        "@odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls("+ phoneCallUid +")"
    };
    

    then

    JSON.stringify(phoneCallAssociationJsonData);
    

    should now work