[Turn] use Json.Net in C # serialization and de-serialization and customized using Json.Net be in C # serialization and de-serialization and customization

Author: Minotauros

Original Address: Use Json.Net in C # serialization and de-serialization and customization

Serialization (the Serialize) is to convert the object into a byte stream, and a process for storage or transmission, the main purpose is to preserve the state of the object to re-create the object when required; deserialize (the Deserialize) is the upper stream of bytes into a corresponding target process; camp in .Net, JSON.NET officially recommended open performance serialization / deserialization tool official website: HTTPS: //www.newtonsoft. COM / json ;

  First, the target sequence into a format string Json

  The first is a normal sequence of operation, for a given class:

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

  Examples of the class Json format string into a sequence of first reference namespace Newtonsoft.Json:

MyClass myClass = new MyClass { MyNum = 10, MyStr = "Hello World" };
Console.WriteLine(JsonConvert.SerializeObject(myClass));

  Print results:

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

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

Console.WriteLine(JsonConvert.SerializeObject(myClass, Formatting.Indented));

  A print results:

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

  Second, the format string Json deserialize objects

  For a given string:

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

  It is deserialized into an object of type MyClass:

MyClass myClass = JsonConvert.DeserializeObject<MyClass>(jsonStr);
Console.WriteLine(myClass.MyStr); //Hello World

  Third, the use of dynamic JObject serialization / deserialization

  Examples of the above sequence is performed using strongly typed and deserialized operation, but the situation does not specify the type sometimes used to directly operate Json data format, then you need to use the namespace JObject type of ewtonsoft.Json.Linq Object:

Copy the code
string jsonStr = @"{""MyNum"": 10,""MyStr"": ""Hello World""}";
JObject jObject = JObject.Parse(jsonStr);
Console.WriteLine(jObject.ToString(Formatting.None));  //{"MyNum":10,"MyStr":"Hello World"}
//打印一条属性的值
Console.WriteLine(jObject["MyStr"].Value<string>());  //Hello World
//添加一条属性
jObject.Add("MyStr2", "HaHa");
//打印当前Json字符串
Console.WriteLine(jObject.ToString(Formatting.None)); //{"MyNum":10,"MyStr":"Hello World","MyStr2":"HaHa"}
Copy the code

  Fourth, customized serialization / de-serialization process

  1. In C #, customized using configuration properties generally done, is no exception, such as a simple, ignoring a field / attribute during serialization / deserialization:

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

  In this case, regardless of the sequence or reverse order of the time, field MyNum are no longer involved in these processes;

  2. Customize a field / attribute serialization / de-serialization rules:

  When receiving the format string and the local Json known type are not uniform, the need for custom deserialization process, and vice versa, e.g. Json string to the string "TRUE" represents the Boolean true (not customize when this process is still to go through, but this example), the string "fALSE" represents the boolean false, you need to customize as follows:

Copy the code
/// <summary>
/// 自定义布尔类型数据转换规则
/// </summary>
public class MyBoolConverter : JsonConverter
{
    private const string TrueStr = "TRUE";
    private const string FalseStr = "FALSE";
    public override bool CanConvert(Type objectType) => true;

    //反序列化
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.ValueType == typeof(string))
        {
            if ((string)reader.Value == TrueStr)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    }

    //序列化
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value.GetType() == typeof(bool))
        {
            bool result = (bool)value;
            if (result)
            {
                writer.WriteValue(TrueStr);
            }
            else
            {
                writer.WriteValue(FalseStr);
            }
        }
    }
}
Copy the code

  Then, in the field type definition to be operated / attribute is added the feature:

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

  at this time:

string jsonStr = @"{""MyBool"": ""TRUE""}";
MyClass1 myClass = JsonConvert.DeserializeObject<MyClass1>(jsonStr);
Console.WriteLine(myClass.MyBool);  //True
Console.WriteLine(JsonConvert.SerializeObject(myClass));  //{"MyBool":"TRUE"}

Guess you like

Origin www.cnblogs.com/fanqisoft/p/10941867.html
Recommended