Implementation code for serializing json using ES0en.Text

  • 2020-06-15 08:00:09
  • OfStack

I believe that friends who do.net development often encounter the need of json serialization. Today I will summarize my use of ServiceStack.Text to serialize json. It is much faster than the ES6en.Json and was found to be faster than the fastJson in tests.

First, we have the following two classes, one for the staff (Staff) class and one for the contact information (Contact) class:


public class Staff
{
    public long ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
public class Contact
{
    public long StaffID { get; set; }
    public string Email { get; set; }
}

First, we add two staff members:


List<Staff> listStaff = new List<Staff>();
listStaff.Add(new Staff() { ID = 2, Name = " Xiao li " });
listStaff.Add(new Staff() { ID = 3, Name = " wang " });

The way many people serialized json before:


var result = "[";
foreach (var staff in listStaff)
{
    result += "{\"ID\":\"" + staff.ID + "\",\"Name\":\"" + staff.Name + "\"},";
}
result = result.Substring(0, result.Length - 1);
result += "]";

The final json is as follows:

[
    {
        "ID": "2",
        "Name": " Xiao li "
    },
    {
        "ID": "3",
        "Name": " wang "
    }
]

This is fine, but it has a few drawbacks: 1. The code is cluttered and error-prone. 2. You need to escape special characters, such as double quotes, otherwise the json serialization will fail. Let's look at serializing json using ES33en.Text.

We need to download ServiceStack.Text.dll, reference it to our project, and reference the ES41en.Text namespace. Here's a look at the serialization of a single class object:


Staff staff = new Staff() { ID = 1, Name = "xiaozhao" };
var result = staff.ToJson();

json is obtained as follows:


{
    "ID": 1,
    "Name": "xiaozhao",
    "Age": 0
}

Careful friends will notice that we did not intend to use the Age attribute in the output, but here we have Age. To solve this problem, we have the following method.

1. Use the JsonObject class, which inherits from Dictionary < string, string > , so that we can output the desired properties as follows.


Staff staff = new Staff() { ID = 1, Name = "xiaozhao" };
JsonObject json = new JsonObject();
json.Add("ID", staff.ID.ToString());
json.Add("Name", staff.Name);
var result = json.ToJson();

In this way, the following result [result 1] is obtained, which serves our purpose.

{
    "ID": 1,
    "Name": "xiaozhao"
}

2. Add System.Runtime.Serialization to the project and reference the namespace ES74en.Runtime.Serialization.

We can specify the property to serialize on the property, as follows:


[DataContract]
public class Staff
{
    [DataMember]
    public long ID { get; set; }
    [DataMember]
    public string Name { get; set; }
    public int Age { get; set; }
}

Or:


public class Staff
{
    public long ID { get; set; }
    public string Name { get; set; }
    [IgnoreDataMember]
    public int Age { get; set; }
}

The output of the following code would then be the same as [result 1].


Staff staff = new Staff() { ID = 1, Name = "xiaozhao" };
var result = staff.ToJson();

Finally, let's look at the serialization of the collection of class objects. We add the contact information of the staff as follows:


List<Contact> listContact = new List<Contact>();
listContact.Add(new Contact() { StaffID = 3, Email = "xiaowang@163.com" });
listContact.Add(new Contact() { StaffID = 4, Email = "xiaoli@163.com" });

There may be one contact information for each employee. Here, it is necessary to consider that some employees do not have contact information. The code is given directly:


List<string> list = new List<string>();
foreach (var staff in listStaff)
{
    JsonObject json = new JsonObject();
    json.Add("ID", staff.ID.ToString());
    json.Add("Name", staff.Name);
    // contact 
    var contact = listContact.FirstOrDefault(m => m.StaffID == staff.ID);
    if (contact != null)
    {
        JsonObject jsonContact = new JsonObject();
        jsonContact.Add("Email", contact.Email);
        // Notice here that will  Contact  Object serialized json String added to json object 
        json.Add("Contact", contact.ToJson());
    }
    // will json Object serialization is then added to list
    list.Add(json.ToJson());
}
// Get the final json string 
var result = string.Format("[{0}]", string.Join(",", list));

json obtained:


[
    {
        "ID": 2,
        "Name": " Xiao li "
    },
    {
        "ID": 3,
        "Name": " wang ",
        "Contact": {
            "StaffID": 3,
            "Email": "xiaowang@163.com"
        }
    }
]

For deserialization, FromJson() can be used:

var staff = result.FromJson < List < Staff > > ();
This article briefly introduces the use of ES120en.Text to serialize json, hoping to help those who have not used it.

Author: Dongkui


Related articles: