{"id":12210,"date":"2022-09-30T01:38:02","date_gmt":"2022-09-29T20:08:02","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/"},"modified":"2022-09-30T01:38:02","modified_gmt":"2022-09-29T20:08:02","slug":"solved-serialize-list-using-json-net","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/","title":{"rendered":"[Solved] Serialize List using Json.net"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-43312100\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"43312100\" data-parentid=\"43293914\" data-score=\"2\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>Serializing a <code>List&lt;LinkedListNode&lt;string&gt;&gt;<\/code> is a bit of an odd thing to do &#8211; normally one would just serialize the underlying linked list.  Perhaps you&#8217;re trying to serialize a table that gives the nodes in a different order than the underlying list?  <\/p>\n<p>If that&#8217;s the case, it might appear that one could serialize the node list using <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/www.newtonsoft.com\/json\/help\/html\/PreserveReferencesHandlingObject.htm\"><code>PreserveReferencesHandling.All<\/code><\/a> combined with <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/www.newtonsoft.com\/json\/help\/html\/ReferenceLoopHandlingIgnore.htm\"><code>ReferenceLoopHandling.Serialize<\/code><\/a>, however this fails due to some limitations of Json.NET:<\/p>\n<ul>\n<li>\n<p><code>PreserveReferencesHandling<\/code> is not implemented for read-only properties (see <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/github.com\/JamesNK\/Newtonsoft.Json\/issues\/1140\">here<\/a>) but <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/h339c45b(v=vs.110).aspx\"><code>LinkedListNode.List<\/code><\/a>, <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/b4t9w6be(v=vs.110).aspx\"><code>.Next<\/code><\/a> and <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/de80z2x6(v=vs.110).aspx\"><code>.Previous<\/code><\/a> are all read-only.  This prevents correct serialization of circular dependencies and eventually leads to an infinite recursion on the next and previous node properties.<\/p>\n<\/li>\n<li>\n<p><code>PreserveReferencesHandling<\/code> is not implemented for objects with non-default constructors (see <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/github.com\/JamesNK\/Newtonsoft.Json\/issues\/715\">here<\/a>) but the only public constructor for <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/24y0zx74(v=vs.110).aspx\"><code>LinkedListNode&lt;T&gt;<\/code><\/a> is parameterized.<\/p>\n<\/li>\n<\/ul>\n<p>Thus, you will need to create a <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/www.newtonsoft.com\/json\/help\/html\/CustomJsonConverter.htm\">custom <code>JsonConverter<\/code><\/a> for your list of nodes:<\/p>\n<pre><code>public class LinkedListNodeListConverter&lt;T&gt; : JsonConverter\n{\n    public override bool CanConvert(Type objectType)\n    {\n        return typeof(List&lt;LinkedListNode&lt;T&gt;&gt;).IsAssignableFrom(objectType);\n    }\n\n    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n    {\n        if (reader.TokenType == JsonToken.Null)\n            return null;\n        var list = (existingValue as IList&lt;LinkedListNode&lt;T&gt;&gt; ?? (IList&lt;LinkedListNode&lt;T&gt;&gt;)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator());\n        var table = serializer.Deserialize&lt;LinkedListNodeOrderTable&lt;T&gt;&gt;(reader);\n        foreach (var node in table.ToNodeList())\n            list.Add(node);\n        return list;\n    }\n\n    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n    {\n        var list = (IList&lt;LinkedListNode&lt;T&gt;&gt;)value;\n        var table = LinkedListNodeOrderTable&lt;T&gt;.FromList(list);\n        serializer.Serialize(writer, table);\n    }\n}\n\nclass LinkedListNodeOrderTable&lt;T&gt;\n{\n    public static LinkedListNodeOrderTable&lt;T&gt; FromList(IList&lt;LinkedListNode&lt;T&gt;&gt; nodeList)\n    {\n        if (nodeList == null)\n            return null;\n        try\n        {\n            var list = nodeList.Where(n =&gt; n != null).Select(n =&gt; n.List).Distinct().SingleOrDefault();\n            var table = new LinkedListNodeOrderTable&lt;T&gt;(list);\n            var dictionary = list == null ? null : list.EnumerateNodes().Select((n, i) =&gt; new KeyValuePair&lt;LinkedListNode&lt;T&gt;, int&gt;(n, i)).ToDictionary(p =&gt; p.Key, p =&gt; p.Value);\n            table.Indices = nodeList.Select(n =&gt; (n == null ? -1 : dictionary[n])).ToList();\n            return table;\n        }\n        catch (Exception ex)\n        {\n            throw new JsonSerializationException(string.Format(\"Failed to construct LinkedListNodeOrderTable&lt;{0}&gt;\",  typeof(T)), ex);\n        }\n    }\n\n    public LinkedListNodeOrderTable(LinkedList&lt;T&gt; List)\n    {\n        this.List = List;\n    }\n\n    public LinkedList&lt;T&gt; List { get; set; }\n\n    public List&lt;int&gt; Indices { get; set; }\n\n    public IEnumerable&lt;LinkedListNode&lt;T&gt;&gt; ToNodeList()\n    {\n        if (Indices == null || Indices.Count &lt; 1)\n            return Enumerable.Empty&lt;LinkedListNode&lt;T&gt;&gt;();\n        var array = List == null ? null : List.EnumerateNodes().ToArray();\n        return Indices.Select(i =&gt; (i == -1 ? null : array[i]));\n    }\n}\n\npublic static class LinkedListExtensions\n{\n    public static IEnumerable&lt;LinkedListNode&lt;T&gt;&gt; EnumerateNodes&lt;T&gt;(this LinkedList&lt;T&gt; list)\n    {\n        if (list == null)\n            yield break;\n        for (var node = list.First; node != null; node = node.Next)\n            yield return node;\n    }\n}\n<\/code><\/pre>\n<p>And use the following settings:<\/p>\n<pre><code>var settings = new JsonSerializerSettings\n{\n    Converters = { new LinkedListNodeListConverter&lt;string&gt;() },\n};\nstring json = JsonConvert.SerializeObject(lst, Formatting.Indented, settings);\n<\/code><\/pre>\n<p>The resulting JSON will look like:<\/p>\n<pre><code>{\n  \"List\": [\n    \"Kuku\",\n    \"Riku\",\n    \"Ok\"\n  ],\n  \"Indices\": [\n    0,\n    1,\n    2\n  ]\n}\n<\/code><\/pre>\n<p>Note that the converter assumes all the nodes in the list are members of the same underlying <code>LinkedList&lt;T&gt;<\/code>.  If not an exception will be thrown.<\/p>\n<p>Sample <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/dotnetfiddle.net\/moURJn\">fiddle<\/a>.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">1<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Serialize List<LinkedListNode<object>> using Json.net <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Serializing a List&lt;LinkedListNode&lt;string&gt;&gt; is a bit of an odd thing to do &#8211; normally one would just serialize the underlying linked list. Perhaps you&#8217;re trying to serialize a table that gives the nodes in a different order than the underlying list? If that&#8217;s the case, it might appear that one could serialize the node &#8230; <a title=\"[Solved] Serialize List using Json.net\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/\" aria-label=\"More on [Solved] Serialize List using Json.net\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[324,1505,935],"class_list":["post-12210","post","type-post","status-publish","format-standard","hentry","category-solved","tag-c","tag-json-net","tag-serialization"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Serialize List using Json.net - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Serialize List using Json.net - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Serializing a List&lt;LinkedListNode&lt;string&gt;&gt; is a bit of an odd thing to do &#8211; normally one would just serialize the underlying linked list. Perhaps you&#8217;re trying to serialize a table that gives the nodes in a different order than the underlying list? If that&#8217;s the case, it might appear that one could serialize the node ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-29T20:08:02+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Serialize List using Json.net\",\"datePublished\":\"2022-09-29T20:08:02+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/\"},\"wordCount\":185,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"c++\",\"json.net\",\"serialization\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/\",\"name\":\"[Solved] Serialize List using Json.net - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-09-29T20:08:02+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Serialize List using Json.net\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Serialize List using Json.net - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Serialize List using Json.net - JassWeb","og_description":"[ad_1] Serializing a List&lt;LinkedListNode&lt;string&gt;&gt; is a bit of an odd thing to do &#8211; normally one would just serialize the underlying linked list. Perhaps you&#8217;re trying to serialize a table that gives the nodes in a different order than the underlying list? If that&#8217;s the case, it might appear that one could serialize the node ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/","og_site_name":"JassWeb","article_published_time":"2022-09-29T20:08:02+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Serialize List using Json.net","datePublished":"2022-09-29T20:08:02+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/"},"wordCount":185,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["c++","json.net","serialization"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/","url":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/","name":"[Solved] Serialize List using Json.net - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-29T20:08:02+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-serialize-list-using-json-net\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Serialize List using Json.net"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/12210","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=12210"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/12210\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=12210"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=12210"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=12210"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}