【问题标题】:How to pass json array as a string to web api from postman如何将json数组作为字符串从邮递员传递给web api
【发布时间】:2021-04-05 19:18:21
【问题描述】:

邮递员中我的 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

【问题讨论】:

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


    【解决方案1】:

    使用 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 机制的对象数组。

    【讨论】:

      【解决方案2】:

      我已经安装了 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");
      }
      

      【讨论】:

        猜你喜欢
        • 2023-02-22
        • 1970-01-01
        • 2021-07-04
        • 1970-01-01
        • 2023-02-01
        • 1970-01-01
        • 2016-08-13
        • 2015-05-07
        • 1970-01-01
        相关资源
        最近更新 更多