我正在进行服务器到服务器的通信,并且正在从我的 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/