反序列化从 Ajax 传递到 ASP.NET MVC 的 JSON 对象

Deserializing the JSON object passed from Ajax to ASP.NET MVC

我正在尝试通过 Ajax 请求将 JSON 对象发送到 ASP.NET MVC。在后端获取 JSON 对象时,它接收字符串格式的对象,如下所示。

如何将其反序列化为 C# 对象?

C# ASP.NET MVC 代码:

public string GetLists(string list1)
{
    return JsonConvert.SerializeObject(list1, JsonSetting);
}

JavaScript代码:

button.onclick=()=> {
    let xhr = new XMLHttpRequest()     
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.response)
        }
    }
    let list1=[
        {"id":"1a","level":1},
        {"id":"2b","level":14},
        {"id":"3c","level":23}
    ]
    var params ="list1=" + JSON.stringify(list1)
    xhr.open("POST", "/Status/GetLists");
    xhr.setRequestHeader('content-type', "application/x-www-form-urlencoded");
    xhr.send(params);
}

输出:

[
    {\"id\":\"1a\",\"level\":1},
    {\"id\":\"2b\",\"level\":14},
    {\"id\":\"3c\",\"level\":23}
]

您可以使用 System.Text.Json.JsonSerializer 但是您应该包括一个反序列化类型,以便 c# 知道您尝试接收的数据类型。

在您的代码中,您只返回字符串而不是 C# 对象,因此您必须指定一个 class 或一个接口来为您的数据建模。

接收数据的示例片段:

using System;
using System.Collections.Generic;
using System.Text.Json;

// define the structure of the object you want to recieve

interface MyDataStructure
{
    public string id { get; set; }
    public int level { get; set; }

}
class Program
{
    public void ReadData(string jsonData)
    {
        // Creating a list of objects from your type. The Json Serializer is flexible and also workes when using Arrays

        List<MyDataStructure> data = JsonSerializer.Deserialize<List<MyDataStructure>>(jsonData);
        foreach (var obj in data){
            Console.WriteLine($"{obj.id}||{obj.level}");
        }
    }
}

我建议您查看有关反序列化和序列化的文档。

.Net JsonSerializer 的替代品是 Newtonsofts Json.NET

您正在尝试发送一个 json 对象,但 content-type 是错误的 content-type,在您的情况下 content-type 应该是 application/json 并且您不必添加“params”+ JSON.stringify(list1) 因为这将在请求正文中发送,您应该只发送 list1 变量。

xhr.setRequestHeader('content-type', "application/json");
xhr.send(JSON.stringify(list1));

然后您将能够反序列化后端端点中的对象,例如:

    public class Item
    {
        public string id { get; set; }
        public string level { get; set; }
    }

    [HttpPost]
    public List<Item> GetLists([FromBody] object value)
    {
        var items = JsonConvert.DeserializeObject<List<Item>>(value.ToString());

        return items;
    }

你的数据被序列化了两次,一开始你手动序列化它,在这个网络序列化后它自动发送回数据。所以你根本不需要序列化它,net 会为你做。将您的操作更改为此

public ActionResult<List<Item>> GetLists([FromBody] List<item> list)
{
    return Ok(list);
}

class

 public class Item
    {
        public string id { get; set; }
        public string level { get; set; }
    }

和ajax

    var params =JSON.stringify(list1);
    xhr.open("POST", "/Status/GetLists");
    xhr.setRequestHeader('content-type', "application/json");
    xhr.send(params);