Ⅰ 如何將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};";