【问题标题】:How to deserialize multiple JSON objects in C#?如何在 C# 中反序列化多个 JSON 对象?
【发布时间】:2015-09-26 10:35:52
【问题描述】:

我将多个 JSON 对象从我的前端传递到 C# 后端 - 我如何将它们反序列化为 C# 类,以便以后可以在我的应用程序中使用它们?在我走得更远之前,我会使用 JS FormData 对象、contentType: falseprocessData: false,因为我还需要通过这个 AJAX 调用传递文件;这与这个问题完全无关。到目前为止,这是我的代码:

前端 - 按下提交按钮时调用函数

submitData: function () {
    var formCollection = this.appModel.get('formCollection').models;
    var formData = new FormData();
    var formJson = [];
    $.each(formCollection, function (index, form) {
        var tempJson = {};
        if (form) {
            tempJson['id'] = form.get('id');
            tempJson['number'] = form.get('number');
            tempJson['name'] = form.get('name');
            tempJson['attachments'] = form.get('attachments');
            formJson.push(tempJson);
        }
    });
    console.log(JSON.stringify(formJson));
    formData.append('formJson', JSON.stringify(formJson));
    $.ajax({
        type: "POST",
        url: '/NMISProduct/Test',
        contentType: false,
        processData: false,
        data: formData,
        success: function (result) {
            console.log(result);
        }
    });
}

正在传递的 JSON.stringified 数据

[{"id":1,"number":null,"name":"Investment Portfolio Statement","attachments":null},{"id":2,"number":"61-0227","name":"WMC Signature Portfolio Agreement","attachments":null},{"id":3,"number":"61-1126","name":"WMC Signature Choice Agreement","attachments":null},{"id":4,"number":"61-1162","name":"WMC Signature Annuities Agreement","attachments":null},{"id":5,"number":"61-1205","name":"WMC Signature Managed Accounts Client Agreement","attachments":null}]

C# MVC 5 后端

[HttpPost]
public async Task<JsonResult> Test()
{
    Debug.WriteLine(Request.Params["formJson"]);
    var forms = JsonConvert.DeserializeObject<Form>(Request.Params["formJson"]);
    Debug.WriteLine(forms);
    try
    {
        var srNumber = GetSRNumber();
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            Debug.WriteLine(ReadFileInputStream(fileContent));
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                // get a stream
                var stream = fileContent.InputStream;
                // and optionally write the file to disk
                //var fileName = Path.GetFileName(file);
                var fileName = fileContent.FileName;
                var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                using (var fileStream = System.IO.File.Create(path))
                {
                    stream.CopyTo(fileStream);
                }
            }
        }
    }
    catch (Exception)
    {
        return Json("Upload failed");
    }
    return Json("File uploaded successfully");
}

public class Form
{
    public int id { get; set; }
    public string number { get; set; }
    public string name { get; set; }
    public Form attachments { get; set; }
    public byte[] fileAsBytes { get; set; }
}

我已经完成了研究,发现了几个 Stackoverflow 问题,这些问题展示了如何将一个 JSON 对象序列化为一个 C# 类 - 但是,我需要将多个 JSON 对象序列化为一个List&lt;Form&gt;。我怎样才能做到这一点?我在发布的代码中做错了什么?

【问题讨论】:

    标签: javascript c# ajax json asp.net-mvc-5


    【解决方案1】:
    [HttpPost]
    public async Task<JsonResult> Test(List<Form> forms)
    {
        // your code here
    }
    

    然后放上你的 JS 代码

    formJson.push(tempJson);
    

    里面

    if (form)
    

    【讨论】:

      【解决方案2】:

      您正试图在此处反序列化为单个表单:

      var forms = JsonConvert.DeserializeObject<Form>(Request.Params["formJson"]);
      

      只需将其更改为:

      var forms = JsonConvert.DeserializeObject<List<Form>>(Request.Params["formJson"]);
      

      然后您应该能够以正常方式使用forms - 对其进行迭代、计数等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多