【发布时间】:2020-08-28 19:23:47
【问题描述】:
我正在尝试创建一个以 JSON (content-type:application/json) 为主体的 PUT 方法(或 POST,无论哪个有效),然后对其进行迭代,将(键,值)内容写入控制台。我不确定如何将 JSON 作为输入,因为使用 [FromBody] string data 返回以下错误:"The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."。
为了解决这个问题,我使用了dynamic 类型。但是,我无法迭代此数据类型的键值对。输入的 JSON 每次都是随机的,所以我不能为它创建一个类。
PUT 方法:
[HttpPut("{something}")]
public ActionResult update(string something, [FromBody] dynamic data)
{
}
示例 JSON:
{"id":"123","name":"sample name"}
我尝试过的:
以下行:var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
输出错误:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:最好的 重载方法匹配 'Newtonsoft.Json.JsonConvert.DeserializeObject
>(string)' 有一些无效的参数
成功迭代 JSON 数据后的预期输出到控制台:
id: 123
name: some name
【问题讨论】:
标签: c# .net asp.net-web-api