如何将JSON对象传递给Controller进行处理

时间:2025-03-17 17:42:26

Step 1. 利用jQuery的Ajax方法发送JSON数据

$.ajax({
url: "/[Controller]/[Action]",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify([JSON Data]),
async: true,
success: function (result) {}
});

Step 2. Controller接收JSON数据

var jsonString = new StreamReader().ReadToEnd();

Step 3. 解析JSON对象

json为集合时这样解析:

JsonReader reader = new JsonTextReader(new StringReader(jsonString));
List<[Class]> jsonObjects = new JsonSerializer().Deserialize<List<[Class]>>(reader);

json为对象时这样解析:

[Class] jsonObject = <[Class]>(jsonString);

示例: 读取JSON文件中的数据库配置信息生成ConnectionString

JSON文件内容:

{
"server": "localhost",
"database": "calyxmelo",
"uid": "root",
"pwd": ""
}

我们有一个Database类与之对应:

public class Database
{
    public string server { get; set; }
    public string database { get; set; }
    public string uid { get; set; }
    public string pwd { get; set; }
}

生成ConnectionString:

var jsonString = new StreamReader(Request.Body).ReadToEnd();
Database jsonObject = JsonConvert.DeserializeObject(jsonString);
connectionString = $"server={};database={};uid={};pwd={};";