如何将json数组作为字符串从邮递员传递给web api

时间:2020-12-29 04:51:21

标签: json asp.net-web-api postman

我在邮递员中的 Json [Body] 结构如下

[{
  "SerialNumber": "dev1",

  "CustomerId": "cust1",

  "Seed": "c393d900-2f25-819f-cc83-0721357bcf10",

  "BitLockerKey": null,

  "bitLockerRecoveryKey": null

   },

 {

  "SerialNumber": "dev2",

  "CustomerId": "cust2",

  "Seed": "c393d900-2f25-819f-cc83-0721357bcf22",

  "BitLockerKey": null,

  "bitLockerRecoveryKey": null

}]

我的web api函数如下,

    [HttpPost]
    public ActionResult<string> SaveData([FromBody] string Data)
    {
        int result = _seedService.SeedGeneration(Data);
        return result > 0 ? Ok(result) : (ActionResult<string>)UnprocessableEntity("Seed generation 
        Failed");
    }

我的问题是,如何在邮递员中将数据作为具有 json 数组结构的字符串传递。我收到错误“无法将 JSON 值转换为 System.string

2 个答案:

答案 0 :(得分:0)

使用 JSON.stringify(jsonValue),您可以通过 javascript 将 JSON 对象转换为字符串。

结果如下:

"[{"SerialNumber":"dev1","CustomerId":"cust1","Seed":"c393d900-2f25-819f-cc83-0721357bcf10","BitLockerKey":null,"bitLockerRecoveryKey":null},{"SerialNumber":"dev2","CustomerId":"cust2","Seed":"c393d900-2f25-819f-cc83-0721357bcf22","BitLockerKey":null,"bitLockerRecoveryKey":null}]"

您还可以将 action 参数声明为一个对象数组,其中包含您的 Json 结构和您为您处理它的 Asp.Net 机制。

答案 1 :(得分:0)

我已经安装了 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包并修改了功能。删除字符串作为参数并在参数中包含 JsonElement。

[HttpPost]

public ActionResult<string> SaveData([FromBody] JsonElement Data)
{
    string json = System.Text.Json.JsonSerializer.Serialize(Data);
    int result = _seedService.SeedGeneration(json);
    return result > 0 ? Ok(result) : (ActionResult<string>)UnprocessableEntity("Seed 
    generation Failed");
}