.netjson.netodatasap-successfactors

How to deserialize objects from OData SuccessFactors API in .net


I want to read some SuccessFactors (SAP HR System) Data in my .net project. SuccessFactors using OData v2 API's to make data accessible. I use the following code to read a User:

using (var client = new HttpClient())
{
            
 var credential = Encoding.ASCII.GetBytes("username:pwd");
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credential));
            
 var json = await 
 client.GetStringAsync($"https://successfactorsServer.sapsf.eu/odata/v2/User?$filter=userId eq '{userId}'&$select=firstName, lastName");
 var user = JsonConvert.DeserializeObject<User>(json);
 return user;
}

The problem is that the service delivers the

<id>https://api12preview.sapsf.eu/odata/v2/User('MaxMustermann')</id>
<title type="text"></title>
<updated>2022-06-17T20:27:31Z</updated>
<author>
    <name></name>
</author>
<link rel="edit" title="User" href="User('MaxMustermann')"></link>
<category term="SFOData.User" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"></category>
<content type="application/xml">
    <m:properties>
        <d:firstName>Max</d:firstName>
        <d:lastName>Mustermann</d:lastName>
    </m:properties>
</content>

But this is not convertable to my model object:public class User : INotifyPropertyChanged { public User() { }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName => FirstName + " " + LastName;

    public event PropertyChangedEventHandler PropertyChanged;
}

Is there a way with newtonsoft JsonConverter to solve this. So that firstName and lastName are recognized and transfered to a User object? I don't want to build my C# objects exactly in this JSON Structure. And i'm not sure how to handle the d: in front of JSON Property Names.

Is there a better library maybe?


Solution

  • you are getting xml instead of json from Api. If you can't fix Api you will have to convert xml to c# object

               var response = await client.GetAsync(api);
               var xml = await response.Content.ReadAsStringAsync();
               xml="<root>"+xml.Replace("m:","").Replace("d:","")+"</root>";
    
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);
                XmlNode node = xmlDoc.SelectSingleNode("root");
                var rawjson = JsonConvert.SerializeXmlNode(node).Dump();
                
             User user = JObject.Parse(rawjson)["root"]["content"]["properties"].ToObject<User>();