标签:require art har 资料 ted 问题 tin .json 导致
三个实体类,学生类(Student),班级类(StudentClass),年级类(Grade)
学生类与班级类为多对一的关系,班级表的主键为学生表的外键,年级表的主键为学生表的外键
public class Student { [Column("StudentId")] public int Id { get; set; } [Required] [StringLength(200)] public string _Name { get; set; } public int _Sex { get; set; } public DateTime _Birthday { get; set; } public DateTime _AddTime { get; set; } public virtual Department Department { get; set; } public virtual Grade Grades { get; set; } public virtual StudentClass studentclass { get; set; } } public class StudentClass { [Key] [Column("ClassId")] public int Id { get; set; } [Required] [StringLength(30)] public string ClassName { get; set; } public virtual ICollection<Student> student { get; set; } public virtual Department department { get; set; } public virtual Grade grade { get; set; } } public class Grade { [Key] public int GradeId { get; set; } [StringLength(30)] [Required] public string GradeName { get; set; } [StringLength(200)] public string GradeExplain { get; set; } public virtual ICollection<Student> student { get; set; } public virtual List<StudentClass> studentclass { get; set; } public virtual Department department { get; set; } }
查询学生实体类,获取学生实体列表:
var Studentlist = db.Students.OrderByDescending(s => s.Id).Skip(IntDataPageSize * (IntDataPageIndex - 1)).Take(IntDataPageSize).ToList();
使用Newtonsoft.Json反序列化,给前端返回json字符串
string json = JsonConvert.SerializeObject(Studentlist );
报错,循环引用
解决方案:
JsonSerializerSettings jsSettings = new JsonSerializerSettings(); jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; string Datastr = JsonConvert.SerializeObject(classlist, jsSettings);
这样返回json成功,但是列表里面有时间,时间格式异常,没有显示正确的时间格式,
经过摸索,找到解决方案,直接上代码:
JsonSerializerSettings jsSettings = new JsonSerializerSettings(); jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; jsSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; string Datastr = JsonConvert.SerializeObject(Studentlist,Formatting.Indented,jsSettings);
问题解决!
有认说,使用这种方案,不能反序列化,目前没实践过,但是在查找资料的时候,有篇文章,介绍了这种情况的解决方案,直接上地址:
https://blog.csdn.net/xxdddail/article/details/82252765,有空可以实践一下
EF实体类,设置导航属性,导致序列化时出现"循环引用"错误,及序列化时间格式解决方案
标签:require art har 资料 ted 问题 tin .json 导致
原文地址:https://www.cnblogs.com/PiaoYu/p/10269662.html