Newtonsoft JSON serialize list in list

entity-framework-core json.net serialization uwp

Question

I am using a ef core database in my UWP app and have some issues serializing a list containing a list with Newtonsoft JSON.

For a minimal example consider the UWP tutorial from microsoft with the following code

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");
    }
}

when I now want to serialize some data the following way:

using (var db = new BloggingContext())
{
    var dbPost = db.Blogs.Include(x => x.Post).ToList();
    var serialized = JSONClass.Serialize(dbPost);
}

I get an error of type System.StackOverflowException in mscorlib.ni.dll that I enter an infinity loop. As user alanh mentioned in the comments, this behavior can be fixed with setting ReferenceLoopHandling to ReferenceLoopHandling.Ignore in JsonSerializerSettings.

I would prefer to just store the ID of each Post as List<int> instead of List<Post> when serializing the Blog.

Why serializing, if a database is given? I want to share specific database entries and need to serialize them. Also I consider doing this for synchronization with OneDrive, so there is no clash, when editing different database entries on different devices at different times (single user).

1
1
2/17/2017 3:15:04 PM

Popular Answer

Adding this line of code into your Startup class, prevents your loop problem

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

Then you can use the [JsonIgnore] attribute for all those properties that you don't want to be serialized.

Or you can implement your own serializer by extending the JsonConverter class and implementing your own WriteJson, ReadJson and CanConvert methods as shown in here:

implement your own serializer

1
4/24/2017 3:06:10 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow