我在我的UWP应用程序中使用了一个ef核心数据库,并且有一些问题使用Newtonsoft JSON序列化包含列表的列表。Newtonsoft JSON序列化列表中的列表
对于一个小例子,考虑UWP教程从microsoft用下面的代码
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Post { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=minexample.db");
}
}
当我现在想要序列的一些数据的方式如下:
using (var db = new BloggingContext())
{
var dbPost = db.Blogs.Include(x => x.Post).ToList();
var serialized = JSONClass.Serialize(dbPost);
}
我得到类型的错误System.StackOverflowException
在mscorlib.ni.dll
,我输入一个无限循环。正如用户alanh在评论中提到的那样,通过在JsonSerializerSettings
中设置ReferenceLoopHandling
到ReferenceLoopHandling.Ignore
可以修复此行为。
当序列化Blog时,我宁愿将每个帖子的ID
存储为List<int>
而不是List<Post>
。
为什么要序列化,如果给出数据库?我想共享特定的数据库条目并需要序列化它们。此外,我还考虑与OneDrive
进行同步,因此在不同时间(单个用户)在不同设备上编辑不同数据库条目时不会发生冲突。
JsonSerializerSettings,referenceloophandling =忽略HTTP://www.newtonsoft。 com/json/help/html/T_Newtonsoft_Json_ReferenceLoopHandling.htm – alanh
哇,我正在尝试'JsonSerializerSettings',但是'ReferenceLoopHandling.Serialize'。所以现在我可以序列化整个事情。是否还有一种方法可以将PostId序列化为邮件的别名? – user3079834
@ user3079834 - 你能否[编辑]你的问题来解释你最新的评论中解释的新需求? – dbc