OData Syntax and JSON
The last html web resource I wrote seemed to be another routine coding activity. This was a simple graphical indicator to display a light based on a value in a CRM form, and a simple OData query to fetch a single value.
This time I decided to use the following syntax:
http://<servername>/xrmservices/2011/OrganizationData.svc/<Entity>
Set(guid'<guid_value>’)?$select=<list_of_fields>
The Odata query worked as expected but the web resource was not. Nothing was displayed and no error was generated.
After several hours of research and debugging, I found out that the JSON string that was generated had the following format:
This was a little bit different from what my standard parsing routine expected. Basically, the idea was to traverse an array called “results” using this construct:
var retrievedData = new XMLHttpRequest();
retrievedData.open(“GET”, url, false);
retrievedData.setRequestHeader(“Accept”, “application/json”);
retrievedData.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
retrievedData.onreadystatechange = function () { retrieveReqCallBack(this, destination); };
retrievedData.send();
…
var fetchedData = JSON.parse(retrievedData.responseText).d;
for (var i = 0; i < fetchedData.results.length; i++) {
. . . DO SOMETHING HERE
}
Looking at old web resources that fetched multiple records, the JSON string returned was like this:
So, I had a smoking gun and then the fix was relatively easy. I just needed to access the attributes of the returned (single-record) dataset directly:
var dateStart = fetchedData.myAttribute;
. . . DO SOMETHING HERE
But I wasn’t happy just finding a fix to the problem. I needed to find the root of the problem, why was the JSON string different?
The answer was in the OData syntax used. In previous web resources I had used “filter”:
This syntax will fetch the same single record but it will use the equivalent to RetrieveMultiple in the SDK, which automatically wraps the fetched results in an array called “results”.
So, keep that in mind the next time you use OData, that the syntax you choose may have an impact on how the returned dataset needs to be parsed.
Recent Comments