SoFunction
Updated on 2025-03-06

C# for serialization, deserialization and customization

Serialize is a process of converting an object into a byte stream and using it for storage or transmission. Its main purpose is to save the state of the object so that the object can be recreated when needed; Deserialize is a process of converting the above byte stream into the corresponding object; in the .Net camp, it is a high-performance open source serialization/deserialization tool recommended by the official, and its official website: /json;

1. Serialize the object into a Json format string

First, there is a normal serialization operation, for the given class:

private class MyClass
{
  public int MyNum;
  public string MyStr;
}

Serialize an instance of this class into a Json format string, first referencing the namespace:

MyClass myClass = new MyClass { MyNum = 10, MyStr = "Hello World" };
((myClass));

Its printing results:

{"MyNum":10,"MyStr":"Hello World"}

When printing to a local Log file for your own viewing, you can choose to convert to a Json format string with indentation:

((myClass, ));

The printing result is:

{
 "MyNum": 10,
 "MyStr": "Hello World"
}

2. Deserialize Json format strings into objects

For the given string:

string jsonStr = @"{""MyNum"": 10,""MyStr"": ""Hello World""}";

Deserialize it to an object of type MyClass:

MyClass myClass = <MyClass>(jsonStr);
(); //Hello World

3. Dynamic serialization/deserialization using JObject

The above examples are all used to serialize and desequential operations using strong types, but sometimes they also use Json format data directly without specifying the type. At this time, you need to use an object of type JObject located in the namespace:

string jsonStr = @"{""MyNum"": 10,""MyStr"": ""Hello World""}";
JObject jObject = (jsonStr);
(()); //{"MyNum":10,"MyStr":"Hello World"}
//Print the value of an attribute(jObject["MyStr"].Value&lt;string&gt;()); //Hello World
//Add a property("MyStr2", "HaHa");
//Print the current Json string(()); //{"MyNum":10,"MyStr":"Hello World","MyStr2":"HaHa"}

4. Customized serialization/desequence process

1. In C#, customized configurations are usually done using features, and here is no exception, such as simple, ignoring a certain field/attribute when serializing/desequence:

private class MyClass
{
  [JsonIgnore]
  public int MyNum;
  public string MyStr;
}

At this time, the field MyNum no longer participates in these processes, whether serializing or deserializing;

2. Customize the serialization/deserialization rules for a certain field/attribute:

When the received Json format string is not unified with the local existing type, a custom deserialization process is required, and vice versa. For example, in the Json string, the string "TRUE" represents the Boolean type true (not customize, this process still works, just use this example), and when the Boolean type false is expressed by the string "FALSE" represents the Boolean type, the following needs to be customized:

/// &lt;summary&gt;
/// Customize Boolean type data conversion rules/// &lt;/summary&gt;
public class MyBoolConverter : JsonConverter
{
  private const string TrueStr = "TRUE";
  private const string FalseStr = "FALSE";
  public override bool CanConvert(Type objectType) =&gt; true;

  //Deserialization  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    if ( == typeof(string))
    {
      if ((string) == TrueStr)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
    return false;
  }

  //Serialization  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    if (() == typeof(bool))
    {
      bool result = (bool)value;
      if (result)
      {
        (TrueStr);
      }
      else
      {
        (FalseStr);
      }
    }
  }
}

Then, add this feature to the fields/attributes in the type definition you want to operate:

private class MyClass
{
  [JsonConverter(typeof(MyBoolConverter))]
  public bool MyBool;
}

at this time:

string jsonStr = @"{""MyBool"": ""TRUE""}";
MyClass1 myClass = <MyClass1>(jsonStr);
(); //True
((myClass)); //{"MyBool":"TRUE"}

The above is all the knowledge points compiled for serialization, deserialization and customization in C# this time. Thank you for your support.