c# - 来自 api c# 的 HttpContent ReadAsAsync map 数据

标签 c# json.net

我正在进行服务器到服务器的通信,并且正在从我的 api 获取数据。我使用 Http Web 客户端来做到这一点。这是我的代码

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;
}

我遇到的问题是我正在以这种格式从服务器获取数据

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

但我想要这样的数据

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

我可能还会更改其他变量名称。原因是我将拥有多个具有相同数据的数据源,但格式或名称会有所不同。所以我想给自己一个集中命名。

是否可以以一种不昂贵(耗时)的方式实现?

最佳答案

默认用于反序列化的JSON.NET支持JsonProperty属性来调整JSON字段名称:

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

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

关于c# - 来自 api c# 的 HttpContent ReadAsAsync map 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47452526/

相关文章:

c# - Json 日期时间问题

c# - 我应该如何解析 JSON,它的键和值的重音被转义而不影响字段值中的转义?

c# - 如何从函数返回键值对

c# - import_type 尝试调用全局

c# - iPad 上的 MonoTouch : How to make text search faster?

c# - OpenXml 数据透视表 : how do you read the total and subtotals in order to display them?

c# - 如何在数据中传递Json参数?

c# - Newtonsoft.JSON serializeobject 返回空 JSON 字符串

c# - 无法将包含 %45 的值传递给 REST API

c# - 我如何使用 DesignData 来帮助开发 Metro 应用程序?