Ⅰ 如何将JSON对象传递给Controller进行处理
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) {}
});123456789
Step 2. Controller接收JSON数据
var jsonString = new StreamReader(Request.Body).ReadToEnd();1
Step 3. 解析JSON对象
json为集合时这样解析:
JsonReader reader = new JsonTextReader(new StringReader(jsonString));
List<[Class]> jsonObjects = new JsonSerializer().Deserialize<List<[Class]>>(reader);12
json为对象时这样解析:
[Class] jsonObject = JsonConvert.DeserializeObject<[Class]>(jsonString);1
示例: 读取JSON文件中的数据库配置信息生成ConnectionString
JSON文件内容:
{
"server": "localhost",
"database": "calyxmelo",
"uid": "root",
"pwd": ""
}123456
我们有一个Database类与之对应:
public class Database
{
public string server { get; set; }
public string database { get; set; }
public string uid { get; set; }
public string pwd { get; set; }
}1234567
生成ConnectionString:
var jsonString = new StreamReader(Request.Body).ReadToEnd();
Database jsonObject = JsonConvert.DeserializeObject(jsonString);
connectionString = $"server={jsonObject.server};database={jsonObject.database};uid={jsonObject.uid};pwd={jsonObject.pwd};";