2017-02-15 22 views
1

我在我的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.StackOverflowExceptionmscorlib.ni.dll,我输入一个无限循环。正如用户alanh在评论中提到的那样,通过在JsonSerializerSettings中设置ReferenceLoopHandlingReferenceLoopHandling.Ignore可以修复此行为。

当序列化Blog时,我宁愿将每个帖子的ID存储为List<int>而不是List<Post>

为什么要序列化,如果给出数据库?我想共享特定的数据库条目并需要序列化它们。此外,我还考虑与OneDrive进行同步,因此在不同时间(单个用户)在不同设备上编辑不同数据库条目时不会发生冲突。

+1

JsonSerializerSettings,referenceloophandling =忽略HTTP://www.newtonsoft。 com/json/help/html/T_Newtonsoft_Json_ReferenceLoopHandling.htm – alanh

+1

哇,我正在尝试'JsonSerializerSettings',但是'ReferenceLoopHandling.Serialize'。所以现在我可以序列化整个事情。是否还有一种方法可以将PostId序列化为邮件的别名? – user3079834

+0

@ user3079834 - 你能否[编辑]你的问题来解释你最新的评论中解释的新需求? – dbc

回答

1

添加此行代码放到你的启动类,可以防止你的循环问题

services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); 

然后你可以使用[JsonIgnore]属性为所有那些你不想被序列化的属性。

或者您也可以通过扩展JsonConverter类,并实现自己的WriteJson, ReadJsonCanConvert方法来实现自己的串行如图这里:

implement your own serializer

相关问题