web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Converting CRM Web Api response JSON to CRM Entity in C#

(0) ShareShare
ReportReport
Posted on by 337

I have been writing some code to access CRM Web API through C# console application.

I am successfully able to fetch data from CRM after registring my app with Azure AD Service and providing client ID to  during authentication process.

Upon  request I am getting  data in JSON format so I decided to create an early bound class for organization service and use it in order to convert JSON to crm entity object. Following is the code which I am using to do that. CrmEntities is  early bound class generated from organization service.

 using (var httpClient = GetHttpClient())
            {
                responseMessage =
                await httpClient.GetAsync(URI + "(" + entityId.ToString() + ")");
                //The URL will change in 2016 to include the API version - api/data/v8.0/systemusers
                if (responseMessage.IsSuccessStatusCode)
                {
                    entitySource =
                        (new_entity)
                            earlyBoundSerializer.ReadObject(responseMessage.Content.ReadAsStreamAsync().Result);
                    entitySource = JsonConvert.DeserializeObject<CrmEntities.new_entity>(responseMessage.Content.ReadAsStringAsync().Result);
                    //jRetrieveResponse = JObject.Parse(responseMessage.Content.ReadAsStringAsync().Result);
                }
                else
                    return null;
            }


Now  here comes issue.

When I am converting Json to  new_Entity  its not throwing any exception but when I look at new_entity object  all the values are empty. no data got populated. any idea how to  overcome this?

*This post is locked for comments

I have the same question (0)
  • Prashanth Kamasamudram Profile Picture
    337 on at

    Note : Please Ignore hte first serialization step, I have just  copied it mistakenly,  actual like which I am talking about is following

     

    entitySource = JsonConvert.DeserializeObject<CrmEntities.new_entity>(responseMessage.Content.ReadAsStringAsync().Result);
  • Suggested answer
    Community Member Profile Picture
    on at

    check your json and class,

    -json name must be same member variable. like "empNumber":"123456",

    -json name value contains another json, like   "homeAddress":{"Line1":"123 st","Line2":"apt 1"}

    - json name value contains "aliasNames":{"firstName":"fn1","lastName":"ln1"},{"firstName":"fn2","lastName":"ln2"}] declare list

    public class Employee

       {

           public string empNumber { get; set; }

    public Address homeAddress { get; set; }

    public IList<Names> aliasNames { get; set; }

    }

    public class Address

       {

           public string line1 { get; set; }

           public string line2 { get; set; }

       }

    public class Names

       {

           public string firstName { get; set; }

           public string lastName { get; set; }

       }

    if the above things is not defined and declared properly, your

    Employee objOD = JsonConvert.DeserializeObject<Employee>(respJSON); won't convert to object.

    If my response is helps you, please mark as "Verified"

  • Suggested answer
    Community Member Profile Picture
    on at

    use Odata Client Generator to Generate Entities

    [View:https://yanivrdt.wordpress.com/2015/09/27/crm-web-api-preview-generate-strongly-typed-objects-from-metadata-document/:750:50]

                   if (retrieveResponse.IsSuccessStatusCode)

                   {

                       var Content = await retrieveResponse.Content.ReadAsStringAsync();

                       ODataResponse<T>  odataresponse = JsonConvert.DeserializeObject<ODataResponse<T>>(Content);

                   }

    public class ODataResponse<T>

    {

           public T[] Value { get; set; }

      }

  • cwarren Profile Picture
    on at

    Sumair, thank you for this post.  It is working for me.  Have you seen a way to generate the strongly typed classes with fields for the formatted values?  For example, I can pass this in the JSON request.

    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");

    And this returns the picklist friendly name, but there is no field within the class to deserialize this into.

  • CliveOld Profile Picture
    52 on at

    Has anyone found a way to get the formatted values into the early bound class generated by the odata client? 

  • Suggested answer
    Community Member Profile Picture
    on at

    Getting Optionset formatted values:

    string fetchXmlNewQueryLead = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

    <entity name='lead'>
    <attribute name='industrycode' />
    <order attribute='fullname' descending='false' />
    <filter type='and'>
    <condition attribute='leadid' operator='eq' value='" + entityLead.Id.ToString() + @"' />
    </filter>
    </entity>

    </fetch>";

    EntityCollection objLead = service.RetrieveMultiple(new FetchExpression(fetchXmlNewQueryLead));

    string industry = string.Empty;

    foreach (var c in objLead.Entities)
    {
        if (c.Attributes.Contains("industrycode"))
            industry = c.FormattedValues["industrycode"].ToString();
        else
            industry = string.Empty;
    }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans