使用Json.Net處理json序列化和反序列化接口或繼承類

之前一直沒有怎麼關注過Newtonsoft的Json.Net這個第三方的.NET Json框架,主要是我之前在開發項目的時候大多數使用的都是.NET自帶的Json序列化類JavaScriptSerializer,可是最近在項目中須要序列化和反序列化一個實現接口的類,而若是使用JavaScriptSerializer的話就會出現問題,咱們來看看以下場景。json

 

首先咱們有一個接口IPeople和一個實現了該接口的類Manapp

interface IPeople
{
    string Name { get; set; }
    int Age { get; set; }
}

class Man : IPeople
{
    public string Name { get; set; }

    public int Age { get; set; }
}


咱們使用JavaScriptSerializer直接序列化IPeople接口框架

IPeople poeple = new Man();
poeple.Age = 25;
poeple.Name = "Scott";

JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string textJson = jsSerializer.Serialize(poeple);
poeple = jsSerializer.Deserialize<IPeople>(textJson);

會獲得序列化後的json文本textJson以下函數

{"Name":"Scott","Age":25}

咱們能夠看到在序列化後的json中沒有任何屬性說明這段json究竟是由什麼類序列化而來的,緊接着在JavaScriptSerializer執行jsSerializer.Deserialize<IPeople>(textJson)作反序列化的時候就拋出了異常提示IPeople沒有默認無參構造函數,也就是說JavaScriptSerializer不知道應該把textJson中的json反序列化爲類Man。
ui

 

而若是咱們使用的是Json.NET的話,就能夠完美的實現接口IPeople的序列化和反序列化,咱們來看看怎麼使用Json.NET的序列化和反序列化this

IPeople poeple = new Man();
poeple.Age = 25;
poeple.Name = "Scott";

JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.TypeNameHandling = TypeNameHandling.All;//這一行就是設置Json.NET可以序列化接口或繼承類的關鍵,將TypeNameHandling設置爲All後,Json.NET會在序列化後的json文本中附加一個屬性說明json究竟是從什麼類序列化過來的,也能夠設置TypeNameHandling爲Auto,表示讓Json.NET自動判斷是否須要在序列化後的json中添加類型屬性,若是序列化的對象類型和聲明類型不同的話Json.NET就會在json中添加類型屬性,反之就不添加,可是我發現TypeNameHandling.Auto有時候不太好用。。。
string textJson = JsonConvert.SerializeObject(poeple, jsonSerializerSettings);//將JsonSerializerSettings做爲參數傳入序列化函數,這樣序列化後的Json就附帶類型屬性
poeple = JsonConvert.DeserializeObject<IPeople>(textJson, jsonSerializerSettings);//將JsonSerializerSettings做爲參數傳入反序列化函數,這樣Json.NET就會讀取json文本中的類型屬性,知道應該反序列化成什麼類型

這裏IPeople接口能被成功序列化和返序列化的關鍵就是jsonSerializerSettings.TypeNameHandling = TypeNameHandling.All這行代碼,咱們來看看Json.NET序列化後的json文本信息spa

{"$type":"Json.Man, Json","Name":"Scott","Age":25}

能夠看到Json.NET在序列化後的json文本中添加了一個屬性叫$type來講明json是從Json.Man類序列化而來的,那麼後面再反序列化的時候Json.NET就成功地將上面的json文本反序列化成了類Man.code

 

因此Json.NET在作json的序列化和反序列化的時候比JavaScriptSerializer更全面,固然在使用JavaScriptSerializer的時候自定義Converter也能夠作到序列化接口和繼承類,可是這要麻煩不少。這一點也會讓我之後更多使用Json.NET來實現json的序列化和反序列化。orm

 

給出一個設置TypeNameHandling.Auto的例子說明,是老外寫的,我以爲將TypeNameHandling.Auto解釋得很清楚了。對象

Json.Net has a setting that intelligently adds type information - declare it like this:

new JsonSerializer { TypeNameHandling = TypeNameHandling.Auto };

This will determine whether type embedding is required and add it where necessary. Lets say I had the following classes:

public class Message
{
    public object Body { get; set; }
}

public class Person
{
    public string Name { get; set; }
}

public class Manager : Person
{

}

public class Department
{
    private List<Person> _employees = new List<Person>();
    public List<Person> Employees { get { return _employees; } }
}

 

Notice the Message Body is of type object, and that Manager subclasses Person. If I serialize a Message with a Department Body that has a single Manager I get this:

{
    "Body":
    {
        "$type":"Department, MyAssembly",
        "Employees":[
            {
                "$type":"Manager, MyAssembly",
                "Name":"Tim"
            }]
    }
}


Notice how it's added the $type property to describe the Department and Manager types. If I now add a Person to the Employees list and change the Message Body to be of type Department like this:

public class Message
{
    public Department Body { get; set; }
}

 

then the Body type annotation is no longer needed and the new Person is not annotated - absence of annotation assumes the element instance is of the declared array type. The serialized format becomes:

{
    "Body":
    {
        "Employees":[
            {
                "$type":"Manager, MyAssembly",
                "Name":"Tim"
            },
            {
                "Name":"James"
            }]
    }
}

This is an efficient approach - type annotation is only added where required. While this is .NET specific, the approach is simple enough to handle that deserializers/message types on other platforms should be fairly easily extended to handle this.

I'd be reticent about using this in a public API though, as it is non-standard. In that case you'd want to avoid polymorphism, and make versioning and type information very explicit properties in the message.

 

最後經過我寫的一個例子來演示怎麼自定義和使用Json.Net的轉換器,這個例子還闡述了Json.Net在序列化和反序列化實現了接口IEnumerable的類時所遇到的問題,有興趣的朋友能夠下載。

JsonNetArraySerialization.rar

相關文章
相關標籤/搜索