I have integrated with internal API and the response comes in XML format which I want it to be in JSON format. All I want is to convert the returned API results to JSON and then do the mapping.
How can I convert XML to JSON and do the mapping?
HttpClient client = new HttpClient();
const string BaseUrl = "myUrl";
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpResponseMessage odsResponse = await client.GetAsync("api method i am consuming");
//trying to convert xml to json
var xx = JsonConvert.SerializeObject(odsResponse, Newtonsoft.Json.Formatting.Indented);
//this null is returning null
Viewmodel.AccountLiteExt acc = JsonConvert.DeserializeObject<Viewmodel.AccountLiteExt>(xx);
if (odsResponse.IsSuccessStatusCode)
{
xx = odsResponse.Content.ReadAsStringAsync().Result;
Console.WriteLine(xx);
Console.ReadLine();
}
XML API Response. I have formatted it online and cut it as it is a big file.
{
"MessageEnvelope": {
"AccountLite": {
"AccountLiteExt": [
{
"Id": "1",
"Status": "Active",
"Type": "Bil",
"CSN": "1",
"Location": "ZIM",
"MasterAccountId": "1",
"Name": "Test"
},
{
"Id": "2",
"Status": "Active",
"Type": "Bil",
"CSN": "2",
"Location": "ZIM",
"MasterAccountId": "2",
"Name": "Test"
},
],
"_xmlns": "Url"
},
"_xmlns": "Url"
}
}
Converted it to C# classes for data mapping
public class AccountLiteExt {
public string Id { get; set; }
public string Status { get; set; }
public string Type { get; set; }
public string CSN { get; set; }
public string Location { get; set; }
public string MasterAccountId { get; set; }
public string Name { get; set; }
}
public class AccountLite {
public List<AccountLiteExt> AccountLiteExt { get; set; }
public string _xmlns { get; set; }
}
public class MessageEnvelope {
public AccountLite AccountLite { get; set; }
public string _xmlns { get; set; }
}
public class Root {
public MessageEnvelope MessageEnvelope { get; set; }
}