使用 JSON 将模型集合发布到 webapi

本文关键字:webapi 集合 JSON 模型 使用 | 更新日期: 2023-09-27 17:56:57

这是我的情况。 我构建了一个旨在填充报表的 Web 服务。 它接收可变数量的"调查结果",然后生成包含所有调查结果的报告。

有没有办法使用 JSON 一次发布多个发现,并将其绑定到 List 对象?

编辑:

因此,更具体地说,调查结果如下所示:

{ 标题: "标题", 描述: "

desc", 评级: "高"}

我希望我的函数看起来像这样:

[HttpPost]
public string Post(IList<Finding> findings){
    //code...
}
public class Finding{
  public string title {get; set;}
  //...
}

所以本质上我想将这些 JSON 发现的数组绑定到 IList 中

更新:我希望能够自动绑定它。 我目前能够通过发布 JSON 字符串(使用 JSON.stringify)来解决

这是我有效的代码:

[HttpPost]
public string Post([FromBody]object jsonString){
IList<Finding> findingList = JsonConvert.DeserializeObject<IList<Finding>>(jsonString.toString());
//...
}

关于如何让它自动绑定而不必转换的任何想法?

使用 JSON 将模型集合发布到 webapi

是的,但是您的问题太笼统了,无法深入回答。使用 HttpRequest 类,可以指定正在发布帖子,并将有效负载设为 JSON blob。该 Blob 可以是对象列表。在服务器端,您可以读取该数据并将其序列化。我建议使用 JSON.NET 来执行此操作。你可以用一种非常静态的方式做到这一点,比如你的列表是类型为 A 或类型B, C, or D的对象的列表,这些对象继承自A。如果在代码中创建这些对象定义 JSON.NET 则可以获取原始 json(这些对象的数组)并将其转换为在代码中定义的对象数组。

json.NET 文档:http://james.newtonking.com/projects/json-net.aspxHttpRequest docs:http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspxHttpRequest 的抽象层:http://restsharp.org/

如果您坚持使用解决方案:

[HttpPost]
public string Post([FromBody]object jsonString){
IList<Finding> findingList = JsonConvert.DeserializeObject<IList<Finding>>     (jsonString.toString());
//...
}

我认为您可以:

[HttpPost]
public string Post(string jsonString){
IList<Finding> findingList = JsonConvert.DeserializeObject<IList<Finding>>     (jsonString);
//...
}

。在您的 ajax 调用中:

    $.ajax({
    ...
    data: JSON.Stringify(data),
    ...
    });

你可以尝试类似的东西(它来自我的代码):

    var LoginFormSubmitHandler = function (e) {
    var $form = $(this);
    // We check if jQuery.validator exists on the form
    if (!$form.valid || $form.valid()) {
        $.post($form.attr('action'), $form.serializeArray())
        ...

。你能显示$form.serializeArray()的值吗?

非常有效。没有丑陋的 JSON 反序列化。

[ResponseType(typeof(Customer))]
public async Task<IHttpActionResult> PostCustomer(IEnumerable<Customer> customers)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    db.Customers.AddRange(customers);
    await db.SaveChangesAsync();
    return StatusCode(HttpStatusCode.Created);
}

并致电:

...api/Customers

开机自检表单正文为:

网址: .../api/

[
  {
    "SampleProperty": "SampleValue1"
    ...
    ...
  },
  {
    "SampleProperty": "SampleValue2"
  }
]