我有一项任务要从我的c#项目中创建Moodle课程类别,但以下代码总是返回错误响应:"单个结构中缺少必需的键:categories";我的代码如下:
string sitename = "http://localhost/moodle";
string token = "0d31f83da49cc21f8dc599fab4b299f0";
string url = sitename + "/webservice/rest/server.php?wstoken=" + token + "&wsfunction=core_course_create_categories&moodlewsrestformat=json";
category cat = new category();
List<category> categories = new List<category>();
cat.name = HttpUtility.UrlEncode("2019");
cat.parent = int.Parse(HttpUtility.UrlEncode("2"));
cat.idnumber = HttpUtility.UrlEncode("11");
cat.description = HttpUtility.UrlEncode("Academic year 2019");
cat.descriptionformat = int.Parse(HttpUtility.UrlEncode("1"));
cat.theme = HttpUtility.UrlEncode("");
categories.Add(cat);
Dictionary<string, List<category>> param = new Dictionary<string, List<category>>();
param.Add("categories", categories.ToList());
string jsonList = JsonConvert.SerializeObject(param.ToArray(), Formatting.None);
var client = new RestClient(url);
var request = new RestRequest();
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(jsonList);
request.Method = Method.POST;
var response = client.Execute(request);
//类别类代码
public class category
{
public string name { get; set; }
public int parent { get; set; }
public string idnumber { get; set; }
public string description { get; set; }
public int descriptionformat { get; set; }
public string theme { get; set; }
public category()
{
descriptionformat = 1;
theme = "";
}
}
string sitename = "http://localhost/moodle";
string token = "0d31f83da49cc21f8dc599fab4b299f0";
string url = sitename + "/webservice/rest/server.php?wstoken=" + token + "&wsfunction=core_course_create_categories&moodlewsrestformat=json";
category cat = new category();
List<category> categories = new List<category>();
cat.name = HttpUtility.UrlEncode("2019");
cat.parent = int.Parse(HttpUtility.UrlEncode("0"));
cat.idnumber = HttpUtility.UrlEncode("11");
cat.description = HttpUtility.UrlEncode("Academic year 2019");
cat.descriptionformat = int.Parse(HttpUtility.UrlEncode("1"));
cat.theme = HttpUtility.UrlEncode(String.Empty);
var client = new RestClient(url);
var request = new RestRequest();
request.AddHeader("Content-Type", "application/json");
request.AddParameter("categories[0][name]", "'" + cat.name + "'", ParameterType.QueryString);
request.AddParameter("categories[0][parent]", cat.parent, ParameterType.QueryString);
request.AddParameter("categories[0][idnumber]", "'" + cat.idnumber + "'", ParameterType.QueryString);
request.AddParameter("categories[0][description]", "'" + cat.description + "'", ParameterType.QueryString);
request.AddParameter("categories[0][descriptionformat]", cat.descriptionformat, ParameterType.QueryString);
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
var response = client.Execute(request);