gpt4 book ai didi

c# - 我应该在 Web API 2 中将哪种形式的 JSON 与 Dictionary 一起使用?

转载 作者:行者123 更新时间:2023-11-30 17:38:44 27 4
gpt4 key购买 nike

通常在 Web API 中将 JSON 与 C# 模型绑定(bind)非常简单,但我发现 Dictionary<string, string>使用它非常困难。

我有一个模型,比如说 Foo ,其属性类型为 Bar :

public Bar SomeProp { get; set; }

Bar 有简单的字典:

public class Bar
{
public Dictionary<string, string> SomeDict { get; set; }
}

看起来很简单,当我得到这种对象时,Web API 会生成以下 JSON:

"SomeProp": {
"Bar":
{
"key": "val",
"key2": "val2"
}
}

问题出在反向的东西上。当我尝试在请求中使用相同的 JSON 时,Web API 不会将其绑定(bind)到参数模型。

我做错了什么?

最佳答案

我想传输一个数据容器,其属性为“ExcelRanges”,它是一个字典。我没有设法使用 Dictionary 作为属性的目标类型。

作为解决方法,我使用了一个列表,其条目由一个自定义类“Range”组成,具有一个名称和一个值属性:

/// <summary>
/// Container for data that should be written to an Excel file
/// </summary>
public class ExcelData
{
public Guid Id { get; set; }
public List<Range> ExcelRanges { get; set; }
}

public class Range
{
public string Name { get; set; }

public List<List<object>> Values { get; set; }
}


[HttpPost]
[Route("Measures")]
public Guid Measures(ExcelData excelData)
{
...
}

function execute(site, filteredMeasures) {

var excelRanges = [
{
'Name': 'additionalInvestmentEfficiency',
'Values': [[1,2],[3,4]]
},
{
'Name': 'totalInvestment',
'Values': [[10,20],[30,40]]
}
];

var data = {
'Id': site.siteId(),
'ExcelRanges': excelRanges
};

return $.ajax({
url: routeConfig.exportMeasureDataByUrl,
type: 'POST',
contentType: 'application/json',
processData: false,
data: JSON.stringify(data),
headers: appSecurity.getSecurityHeaders()
}).done(function(downloadId) {
window.location.href = routeConfig.exportMeasureDataByUrl + '?downloadId=' + downloadId;
});


}

关于c# - 我应该在 Web API 2 中将哪种形式的 JSON 与 Dictionary<string,string> 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36356030/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com