我有这个结构:
public class StudentNew
{
public int StudentId { get; set; }
...
}
public class RootObjectNew
{
public List<StudentNew> StudentsNew { get; set; }
public int test { get; set; }
}
我想将属性设置为StudentsNew。
RootObjectNew RootObjectNewObject = new RootObjectNew();
RootObject obj = JsonConvert.DeserializeObject<RootObject>(Out);
int i = -1;
foreach (var stu in obj.Students)
{
i++;
RootObjectNewObject.StudentsNew[i].StudentId = stu.Id;
RootObjectNewObject.test = 123;
}
但得到错误:
2018-03-03T09:18:55.628 [Info] Compilation succeeded.
2018-03-03T09:18:56.971 [Info] C#************************
2018-03-03T09:18:57.386 [Error] Exception while executing function: Functions.fGetStudentBySkudId. Microsoft.Azure.WebJobs.Script: One or
more errors occurred. f-fGetStudentBySkudId__-2136340708: Object
reference not set to an instance of an object.
如果我评论
RootObjectNewObject.StudentsNew[i].StudentId = stu.Id;
我得到状态= 200 我做错了什么???
答案 0 :(得分:2)
您必须在RootObjectNewObject中创建StudentNew实例:
RootObjectNew RootObjectNewObject = new RootObjectNew();
RootObjectNewObject.StudentsNew = new List<StudentNew>();
RootObject obj = JsonConvert.DeserializeObject<RootObject>(Out);
foreach (var stu in obj.Students)
{
var st = new StudentNew{
StudentId=Stu.Id,
...
};
RootObjectNewObject.StudentsNew.Add(st);
}