{"id":72197,"date":"2022-07-13T08:00:07","date_gmt":"2022-07-13T06:00:07","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=72197"},"modified":"2024-04-04T18:09:07","modified_gmt":"2024-04-04T16:09:07","slug":"csharp-object-into-json-string-dotnet","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/","title":{"rendered":"How to Turn a C# Object Into a JSON String in .NET?"},"content":{"rendered":"<p>In this article, we&#8217;re going to learn how to serialize a C# object into a JSON string using the two main JSON libraries in the .NET ecosystem. Also, we&#8217;re going to learn how to control different aspects of the serialization process.<\/p>\n<div style=\"padding: 20px; border-left: 5px color:#dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for the video, visit our <a href=\"https:\/\/www.patreon.com\/posts\/source-code-c-to-99787255?src=csharpObjectToJsonString\" target=\"_blank\" rel=\"nofollow noopener\">Patreon page<\/a> (YouTube Patron tier).<\/div>\n<p>Let&#8217;s start.<\/p>\n<hr \/>\r\n<p style=\"text-align: center;\"><strong>VIDEO<\/strong>: Convert a C# Object to JSON Using System.Text.JSON and Newtonsont.JSON.<\/p>\r\n<p style=\"text-align: center;\"><iframe width=\"560\" height=\"315\" src=https:\/\/www.youtube.com\/embed\/nyYK3sTFEW0?si=KSDhY3tIj_iD2zSJ frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen=\"allowfullscreen\"><\/iframe><\/p>\r\n<hr \/>\n<h2>Serialize C# Object Into JSON Strings Using System.Text.Json<\/h2>\n<p>Since .NET Core 3.0, <code>System.Text.Json<\/code> is included in the framework by default. <strong>This is the official Microsoft JSON serialization and deserialization solution<\/strong>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"8\">var obj = new Product\r\n{\r\n    Name = \"Red Apples\",\r\n    Stock = 100,\r\n    DateAcquired = DateTime.Parse(\"2017-08-24\")\r\n};\r\n\r\nvar jsonString = JsonSerializer.Serialize(obj);<\/pre>\n<p>Here, we see how we can use the <code>Serialize()<\/code> static method of the <code>JsonSerializer<\/code> to get the JSON string that results from an object passed as a parameter:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\"Name\":\"Red Apples\",\"Stock\":100,\"DateAcquired\":\"2017-08-24T00:00:00\"}<\/code><\/p>\n<h2>Using Newtonsoft Json.NET to Serialize C# Objects<\/h2>\n<p>In previous versions of the framework, the JSON library that came bundled with .NET was the Newtosoft Json.NET library:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"1\">var jsonString = JsonConvert.SerializeObject(obj);<\/code><\/p>\n<p>Here, we turn an object into a JSON string by calling the <code>SerializeObject()<\/code> static method of the <code>JsonConvert<\/code> object.<\/p>\n<h2>How to Generate Pretty JSON Strings<\/h2>\n<p>Often, we&#8217;ll rather have indented or &#8220;pretty&#8221; JSON strings. We can easily achieve that with <code>System.Text.Json<\/code> by using the <code>WriteIntended<\/code> property of the <code>JsonSerializerOptions<\/code> object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"1-4\">var options = new JsonSerializerOptions\r\n{\r\n    WriteIndented = true\r\n};\r\n\r\nvar jsonString = JsonSerializer.Serialize(obj, options);<\/pre>\n<p>In a similar fashion, Newtosoft has it even easier. We can include the <code>Formatting.Indented<\/code> enumerated value directly in the call to the <code>SerializedObject()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"1\">var jsonString = JsonConvert.SerializeObject(obj, Formatting.Indented);<\/pre>\n<p>In both cases we will obtain a properly formatted JSON string:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-highlight=\"4\">{\r\n  \"Name\": \"Red Apples\",\r\n  \"Stock\": 100,\r\n  \"DateAcquired\": \"2017-08-24T00:00:00\"\r\n}<\/pre>\n<h2>Camel Case Property Names<\/h2>\n<p>Despite being a common formatting option, <strong>none of these libraries will format property names using camel case by default<\/strong>. With <code>System.Text.Json<\/code>, we need to explicitly set the <code>PropertyNamingPolicy<\/code> option in our <code>JsonSerializerOptions<\/code> object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"4\">var options = new JsonSerializerOptions\r\n{\r\n    WriteIndented = true,\r\n    PropertyNamingPolicy = JsonNamingPolicy.CamelCase\r\n};\r\n\r\nvar jsonString = JsonSerializer.Serialize(obj, options);<\/pre>\n<p>Similarly, with Newtonsoft we need to populate the <code>ContractResolver<\/code> property in our <code>JsonSerializerSettings<\/code> with an instance of the <code>CamelCasePropertyNamesContractResolver<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"4\">var options = new JsonSerializerSettings\r\n{\r\n    Formatting = Formatting.Indented,\r\n    ContractResolver = new CamelCasePropertyNamesContractResolver()\r\n};\r\n\r\nvar jsonString = JsonConvert.SerializeObject(obj, options);<\/pre>\n<p>When used this way, both libraries will generate camel case JSON properties when serializing objects:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"name\": \"Red Apples\",\r\n  \"stock\": 100,\r\n  \"dateAcquired\": \"2017-08-24T00:00:00\"\r\n}<\/pre>\n<h2>How to Ignore Certain Properties When Serializing Objects<\/h2>\n<p>Frequently, we&#8217;ll want to prevent some of our object&#8217;s properties from showing up in the resulting JSON string.<\/p>\n<h3>Ignoring NULL Values in Serialization<\/h3>\n<p>One specific scenario is when we do not want to include the properties that contain <code>null<\/code> values. We can use <code>JsonSerializerOptions<\/code> object in <code>System.Text.Json<\/code> to set the <code>DefaultIgnoreCondition<\/code> flag:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"4,5,11\">var obj = new Product\r\n{\r\n    Name = \"Red Apples\",\r\n    Stock = null,\r\n    DateAcquired = null\r\n};\r\n\r\nvar options = new JsonSerializerOptions\r\n{\r\n    WriteIndented = true,\r\n    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull\r\n};\r\n\r\nvar jsonString = JsonSerializer.Serialize(obj, options);<\/pre>\n<p>If we are using Newtonsoft, we&#8217;ll use the <code>NullValueHandling<\/code> property in <code>JsonSerializerSettings<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"4\">var options = new JsonSerializerSettings\r\n{\r\n    Formatting = Formatting.Indented,\r\n    NullValueHandling = NullValueHandling.Ignore\r\n};\r\n\r\nvar jsonString = JsonConvert.SerializeObject(obj, options);\r\n\r\nConsole.WriteLine(jsonString);<\/pre>\n<p>The resulting JSON string will not include any of the null properties:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"Name\": \"Red Apples\"\r\n}<\/pre>\n<h3>Ignoring Specific Properties<\/h3>\n<p>These libraries include <strong>attributes that will let us provide serialization options on a per property basis<\/strong>. The most basic example of this is the <code>JsonIgnore<\/code> attribute that exists in both <code>System.Text.Json<\/code> and Newtonsoft.<\/p>\n<p>We can use the attribute located in the <code>System.Text.Json.Serialization<\/code> namespace on one or more properties in our object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"7\">public class Customer\r\n{\r\n    public string Name { get; set; }\r\n\r\n    public string Address { get; set; }\r\n\r\n    [JsonIgnore]\r\n    public decimal FinancialRating { get; set; }\r\n}<\/pre>\n<p>Consequently, the resulting JSON string will not contain the <code>FinancialRating<\/code> property even though it was present in the original object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"Name\": \"Pumpkins And Roses\",\r\n  \"Address\": \"158 Barfield Rd\"\r\n}<\/pre>\n<p>If we are using Newtonsoft, we can achieve the same result by using the <code>JsonIgnore<\/code> attribute located in the <code>Newtonsoft.Json<\/code> namespace.<\/p>\n<h2>How to Serialize Anonymous and Dynamic Objects<\/h2>\n<p><strong>Both libraries can handle anonymous objects correctly,<\/strong> out of the box:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var obj = new \r\n{ \r\n    FirstName = \"John\", \r\n    LastName = \"Smith\" \r\n};\r\n\r\n\/\/ System.Text.Json\r\nvar jsonStringSystem = JsonSerializer.Serialize(obj, optionsSystem);\r\n\r\n\/\/ Newtonsoft\r\nvar jsonStringNewtonsoft = JsonConvert.SerializeObject(obj, optionsNewtonsoft);<\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"FirstName\": \"John\",\r\n  \"LastName\": \"Smith\"\r\n}<\/pre>\n<p>Similarly, <code>dynamic<\/code> <strong>objects work fine as well with both <\/strong><code>System.Text.Json<\/code><strong> and Newtonsoft<\/strong>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">dynamic dynObj = new ExpandoObject();\r\ndynObj.Name = \"Corey Richards\";\r\ndynObj.Address = \"3519 Woodburn Rd\";\r\n\r\n\/\/ System.Text.Json\r\nvar jsonStringSystem = JsonSerializer.Serialize(dynObj, optionsSystem);\r\n\r\n\/\/ Newtonsoft\r\nvar jsonStringNewtonsoft = JsonConvert.SerializeObject(dynObj, optionsNewtonsoft);<\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"Name\": \"Corey Richards\",\r\n  \"Address\": \"3519 Woodburn Rd\"\r\n}<\/pre>\n<h2>How to Control Date and Time Format<\/h2>\n<p><code>System.Text.Json<\/code> will use <a href=\"https:\/\/code-maze.com\/convert-datetime-to-iso-8601-string-csharp\/\" target=\"_blank\" rel=\"noopener\">ISO-8601-1:2019 format when serializing<\/a> <code>DateTime<\/code> or <code>DateTimeOffset<\/code> properties in our objects, like in this example: <code>2017-08-24T16:59:57-02:00<\/code>. However, we can customize that by creating a custom converter:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class GeneralDateTimeConverter : JsonConverter&lt;DateTime&gt;\r\n{\r\n    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\r\n    {\r\n        return DateTime.ParseExact(reader.GetString() ?? string.Empty, \"G\", new CultureInfo(\"en-US\"));\r\n    }\r\n\r\n    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)\r\n    {\r\n        writer.WriteStringValue(value.ToString(\"G\", new CultureInfo(\"en-US\")));\r\n    }\r\n}<\/pre>\n<p>By using this converter in our serialization code, we will get <code>DateTime<\/code> properties in general date long time format <code>8\/24\/2017 16:59:57 AM<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var options = new JsonSerializerOptions();\r\noptions.Converters.Add(new GeneralDateTimeConverter());\r\n\r\nvar obj = new\r\n{\r\n    DateCreated = new DateTime(2017, 8, 24)\r\n};\r\n\r\nvar jsonString = JsonSerializer.Serialize(obj, options); \/\/ {\"DateCreated\":\"8\/24\/2017 12:00:00 AM\"}<\/pre>\n<p>Alternatively, we can apply our custom converter only to specific properties:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[JsonConverter(typeof(GeneralDateTimeConverter))]\r\npublic DateTime BirthDate { get; set; }<\/pre>\n<p>In Newtonsoft, using a custom date and time format is done in a very similar way. We can create our custom converter that inherits from the <code>Newtonsoft.Json.JsonConverter<\/code> abstract class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class GeneralDateTimeNewtonsoftConverter : JsonConverter\r\n{\r\n    public override bool CanConvert(Type objectType)\r\n    {\r\n        return objectType == typeof(DateTime);\r\n    }\r\n\r\n    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)\r\n    {\r\n        var dataString = reader.Value as string;\r\n        return DateTime.ParseExact(dataString ?? string.Empty, \"G\", new CultureInfo(\"en-US\"));\r\n    }\r\n\r\n    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)\r\n    {\r\n        var dateTimeValue = value as DateTime?;\r\n        writer.WriteValue(dateTimeValue?.ToString(\"G\", new CultureInfo(\"en-US\")));\r\n    }\r\n}<\/pre>\n<p>Once we have our custom converter we can use it either directly in the deserialization process:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var jsonString = JsonConvert.SerializeObject(obj, new GeneralDateTimeNewtonsoftConverter());<\/code><\/p>\n<p>Or by decorating our object&#8217;s properties with the <code>Newtonsoft.Json.JsonConverterAttribute<\/code>.<\/p>\n<h2>Reference Loops<\/h2>\n<p>To understand what a reference loop is, consider the following C# models:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Employee\r\n{\r\n    public string FirstName { get; set; }\r\n    public string LastName { get; set; }\r\n    public Department Department { get; set; }\r\n}\r\n\r\npublic class Department\r\n{\r\n    public string? Name { get; set; }\r\n    public IList&lt;Employee&gt; Staff { get; set; } = new List&lt;Employee&gt;();\r\n}<\/pre>\n<p>Here, we can see how the <code>Employee<\/code> class references the <code>Department<\/code> class that, in turn, references back to the <code>Employee<\/code> class through its <code>Staff<\/code> property.<\/p>\n<p><strong>When trying to turn a circular data structure into a JSON string, we will get an error<\/strong> no matter if we are using <code>System.Text.Json<\/code>:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">JsonException: A possible object cycle was detected.<\/code><\/p>\n<p>Or Newtonsoft:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">JsonSerializationException: Self referencing loop detected with type 'Employee'. Path 'Department.Staff'.<\/code><\/p>\n<h3>Options for Handling Reference Loops<\/h3>\n<p><strong>The best way to avoid this situation is to design our models so they do not contain reference loops<\/strong>. However, if that&#8217;s not possible, JSON libraries offer options to help us deal with circular references.<\/p>\n<p>For <code>System.Text.Json<\/code>, we can set the <code>JsonSerializerOptions.ReferenceHandler<\/code> property to one of the <code>ReferenceHandler<\/code> enumerated value:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"8\">var employee = new Employee { FirstName = \"John\", LastName = \"Smith\" };\r\nvar department = new Department { Name = \"Human Resources\" };\r\nemployee.Department = department;\r\ndepartment.Staff.Add(employee);\r\n\r\nvar options = new JsonSerializerOptions\r\n{\r\n    ReferenceHandler = ReferenceHandler.Preserve\r\n};\r\n\r\nvar jsonString = JsonSerializer.Serialize(department, options);<\/pre>\n<p>Here, we set the <code>ReferenceHandler<\/code> property to <code>ReferenceHandler.Preserve<\/code>. With this, we instruct the serializer to <strong>preserve the object graph structure by including metadata in the serialized objects, and resolve reverence loops using pointers<\/strong> based on generated unique object identifiers:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-highlight=\"2,5,8,12\">{\r\n  \"$id\": \"1\",\r\n  \"Name\": \"Human Resources\",\r\n  \"Staff\": {\r\n    \"$id\": \"2\",\r\n    \"$values\": [\r\n      {\r\n        \"$id\": \"3\",\r\n        \"FirstName\": \"John\",\r\n        \"LastName\": \"Smith\",\r\n        \"Department\": {\r\n          \"$ref\": \"1\"\r\n        }\r\n      }\r\n    ]\r\n  }\r\n}<\/pre>\n<p>Alternatively, we can use the <code>ReferenceHandler.IgnoreCycles<\/code> value to tell the serializer to simply ignore circular references:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"Name\": \"Human Resources\",\r\n  \"Staff\": [\r\n    {\r\n      \"FirstName\": \"John\",\r\n      \"LastName\": \"Smith\",\r\n      \"Department\": null\r\n    }\r\n  ]\r\n}<\/pre>\n<p>On the other hand, with Newtonsoft our only option is to ignore the loop references using the <code>JsonSerializerSettings.ReferenceLoopHandling<\/code> property:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"3\">var options = new JsonSerializerSettings\r\n{\r\n    ReferenceLoopHandling = ReferenceLoopHandling.Ignore\r\n};<\/pre>\n<h2>Conclusion<\/h2>\n<p>In this article, we have learned how to turn a C# object into a JSON string. For that, we learned how to use System.Text.Json and Newtonsoft Json.NET as well.<\/p>\n<p>We&#8217;ve learned how to customize various aspects of the serialization process like indentation, property capitalization, how to ignore specific properties, or how to change the date and time format. We also learned what reference loops are and how to deal with them.<\/p>\n<p>Finally, remember that we can find many other <a href=\"https:\/\/code-maze.com\/introduction-system-text-json-examples\/\" target=\"_blank\" rel=\"noopener\">examples of how to work with System.Text.Json<\/a> on this website.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we&#8217;re going to learn how to serialize a C# object into a JSON string using the two main JSON libraries in the .NET ecosystem. Also, we&#8217;re going to learn how to control different aspects of the serialization process. Let&#8217;s start. Serialize C# Object Into JSON Strings Using System.Text.Json Since .NET Core 3.0, [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[10,927,1157,928,1158],"class_list":["post-72197","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-net","tag-json","tag-newtonsoft-json","tag-serialization","tag-system-text-json","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Turn a C# Object Into a JSON String in .NET? - Code Maze<\/title>\n<meta name=\"description\" content=\"How to serialize a C# object into a JSON string? We&#039;re going to learn how to customize different aspects of the serialization process.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Turn a C# Object Into a JSON String in .NET? - Code Maze\" \/>\n<meta property=\"og:description\" content=\"How to serialize a C# object into a JSON string? We&#039;re going to learn how to customize different aspects of the serialization process.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-07-13T06:00:07+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-04T16:09:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"How to Turn a C# Object Into a JSON String in .NET?\",\"datePublished\":\"2022-07-13T06:00:07+00:00\",\"dateModified\":\"2024-04-04T16:09:07+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/\"},\"wordCount\":923,\"commentCount\":5,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\".NET\",\"JSON\",\"Newtonsoft.Json\",\"Serialization\",\"System.Text.Json\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/\",\"url\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/\",\"name\":\"How to Turn a C# Object Into a JSON String in .NET? - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-07-13T06:00:07+00:00\",\"dateModified\":\"2024-04-04T16:09:07+00:00\",\"description\":\"How to serialize a C# object into a JSON string? We're going to learn how to customize different aspects of the serialization process.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Turn a C# Object Into a JSON String in .NET?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Turn a C# Object Into a JSON String in .NET? - Code Maze","description":"How to serialize a C# object into a JSON string? We're going to learn how to customize different aspects of the serialization process.","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:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/","og_locale":"en_US","og_type":"article","og_title":"How to Turn a C# Object Into a JSON String in .NET? - Code Maze","og_description":"How to serialize a C# object into a JSON string? We're going to learn how to customize different aspects of the serialization process.","og_url":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/","og_site_name":"Code Maze","article_published_time":"2022-07-13T06:00:07+00:00","article_modified_time":"2024-04-04T16:09:07+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"How to Turn a C# Object Into a JSON String in .NET?","datePublished":"2022-07-13T06:00:07+00:00","dateModified":"2024-04-04T16:09:07+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/"},"wordCount":923,"commentCount":5,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":[".NET","JSON","Newtonsoft.Json","Serialization","System.Text.Json"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/","url":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/","name":"How to Turn a C# Object Into a JSON String in .NET? - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-07-13T06:00:07+00:00","dateModified":"2024-04-04T16:09:07+00:00","description":"How to serialize a C# object into a JSON string? We're going to learn how to customize different aspects of the serialization process.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-object-into-json-string-dotnet\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Turn a C# Object Into a JSON String in .NET?"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/72197","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=72197"}],"version-history":[{"count":9,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/72197\/revisions"}],"predecessor-version":[{"id":116288,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/72197\/revisions\/116288"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=72197"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=72197"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=72197"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}