Json serialize and deserialize in C#
Serializing objects is converting an object into a stream of bytes. The goal is to store or transmit the data. This article will teach you how to serialize C# objects to JSON string. We will learn how to convert an object into a JSON string through the JsonConvert class.
First create a simple class we will be using to serialize & deserialize:
public class Item{ public int Id { get; set; } public string Description { get; set; } public string Name { get; set; }}
Next we create a class that will be using the JsonNamingPolicy:
public class ToLowerCasingPolicy : JsonNamingPolicy{ public override string ConvertName(string name) { return name.ToLower(); }}
This Policy can be used very easy:
var options = new JsonSerializerOptions{ PropertyNamingPolicy = new ToLowerCasingPolicy(), WriteIndented = true};
var item = new Item{ Name = "Test", Description = "Test description", Id = 1};
var itemJsonString = JsonSerializer.Serialize(item, options);Console.WriteLine(itemJsonString);
var backToItem = JsonSerializer.Deserialize<Item>(itemJsonString, options);
Output from the itemJsonString:
{"id": 1,"description": "Test description","name": "Test"}