mohsinali1317
mohsinali1317

Reputation: 4425

HttpContent ReadAsAsync map data coming from api c#

I am doing server to server communication and I am getting data back from my api. I using Http web client to do that. This is my code

public async Task<List<Report>> GetReports(string tokenType, string token, int page, int count)
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, token);


    var builder = new UriBuilder(ApiEndPointBase + "api/" + ApiVersion + "/LibraryDocument");
    builder.Port = -1;
    var query = HttpUtility.ParseQueryString(builder.Query);
    query["page"] = page.ToString();
    query["count"] = count.ToString();
    builder.Query = query.ToString();
    string url = builder.ToString();

    var result = await client.GetAsync(url);


    if (!result.IsSuccessStatusCode)
        throw new Exception("");

    List<Report> reports = new List<Report>();
    await result.Content.ReadAsAsync<List<Report>>().ContinueWith(response =>
   {
       reports = response.Result;
   });
    return reports;
}

The issue I am having is that I am getting data from server in this format

public class Report 
{
    public int pK_LibraryDocument { get; set; }
    public string fileName { get; set; }
    public List<string> AvailableForModules { get; set; }
}

But I want data like this

public class Report 
{
    public int id{ get; set; }
    public string fileName { get; set; }
    public List<string> AvailableForModules { get; set; }
}

I would probably have other variable name changes as well. The reason for that is that I would have multiple data sources with same data but the format or name would be different. So I want to have a centralize naming for my self.

Is it possible in a not expensive (time consuming) way.

Upvotes: 2

Views: 1268

Answers (1)

CodeFuller
CodeFuller

Reputation: 31312

JSON.NET that is used by default for deserialization supports JsonProperty attribute for adjusting JSON field name:

public class Report 
{
    [JsonProperty("pK_LibraryDocument")]
    public int id { get; set; }

    public string fileName { get; set; }
    public List<string> AvailableForModules { get; set; }
}

Upvotes: 4

Related Questions