【问题标题】:Receive JSON from body and iterate over it从正文接收 JSON 并对其进行迭代
【发布时间】: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


【解决方案1】:

只要我发布问题 - 我就会找到答案

[HttpPut("{something}")]
public ActionResult update(string something, [FromBody] Dictionary<string, string> data)
{
    foreach (KeyValuePair<string, string> value in data)
    {
        Console.WriteLine(value);

    }
}

我可以将字典作为输入 - 这大概允许 C# 为我反序列化 JSON。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2018-01-15
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2017-08-21
    相关资源
    最近更新 更多