Json.NET使用入门(二)【反序列化】

来源:互联网 发布:js点击之前事件 编辑:程序博客网 时间:2024/05/17 23:47

人生在世,一切都是机缘,顺其自然,内心就会逐渐清朗,生活,也是一首陪伴一生的乐曲。有时它激昂高亢,有时它曲折婉转,有时它忧郁沉闷。生活是快乐的,还是令人难以接受的,这取决于自己的心态。


DeserializeDemo.aspx内容:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DeserializeDemo.aspx.cs" Inherits="NewtonsoftDemo.DeserializeDemo" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">    <head runat="server">        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <title></title>    </head>    <body>        <form id="form1" runat="server">            <div>                <table>                    <tr>                        <td>                            <asp:Button ID="btnDeserializeAnObject" runat="server" Text="反序列化一个对象" OnClick="btnDeserializeAnObject_Click" />                        </td>                        <td>                            <asp:Button ID="btnDeserializeACollection" runat="server" Text="反序列化一个集合" OnClick="btnDeserializeACollection_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnDeserializeADictionary" runat="server" Text="反序列化一个字典" OnClick="btnDeserializeADictionary_Click" />                        </td>                        <td>                            <asp:Button ID="btnDeserializeAnAnonymousType" runat="server" Text="反序列化一个匿名类型" OnClick="btnDeserializeAnAnonymousType_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnDeserializeADataSet" runat="server" Text="反序列化一个DataSet" OnClick="btnDeserializeADataSet_Click" />                        </td>                        <td>                            <asp:Button ID="btnWithCustomCreationConverter" runat="server" Text="用CustomCreationConverter反序列化" OnClick="btnWithCustomCreationConverter_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnDeserializeJSONFromAfile" runat="server" Text="从文件反序列化JSON" OnClick="btnDeserializeJSONFromAfile_Click" />                        </td>                        <td>                            <asp:Button ID="btnPopulateAnObject" runat="server" Text="填充对象" OnClick="btnPopulateAnObject_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnConstructorHandlingSetting" runat="server" Text="ConstructorHandling设置" OnClick="btnConstructorHandlingSetting_Click" />                        </td>                        <td>                            <asp:Button ID="btnObjectCreationHandlingSettin" runat="server" Text="ObjectCreationHandling设置" OnClick="btnObjectCreationHandlingSetting_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnDefaultValueHandlingSetting" runat="server" Text="DefaultValueHandling设置" OnClick="btnDefaultValueHandlingSetting_Click" />                        </td>                        <td>                            <asp:Button ID="btnMissingMemberHandlingSetting" runat="server" Text="MissingMemberHandling设置" OnClick="btnMissingMemberHandlingSetting_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnNullValueHandlingSetting" runat="server" Text="NullValueHandling设置" OnClick="btnNullValueHandlingSetting_Click" />                        </td>                        <td>                            <asp:Button ID="btnReferenceLoopHandlingSetting" runat="server" Text="ReferenceLoopHandling设置" OnClick="btnReferenceLoopHandlingSetting_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnPreserveReferencesHandlingSetting" runat="server" Text="PreserveReferencesHandling设置" OnClick="btnPreserveReferencesHandlingSetting_Click" />                        </td>                        <td>                            <asp:Button ID="btnDateFormatHandlingSetting" runat="server" Text="DateFormatHandling设置" OnClick="btnDateFormatHandlingSetting_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnDateTimeZoneHandlingSetting" runat="server" Text="DateTimeZoneHandling设置" OnClick="btnDateTimeZoneHandlingSetting_Click" />                        </td>                        <td>                            <asp:Button ID="btnTypeNameHandlingSetting" runat="server" Text="TypeNameHandling设置" OnClick="btnTypeNameHandlingSetting_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnMetadataPropertyHandlingSetting" runat="server" Text="MetadataPropertyHandling设置" OnClick="btnMetadataPropertyHandlingSetting_Click" />                        </td>                        <td>                            <asp:Button ID="btnContractResolverSetting" runat="server" Text="ContractResolver设置" OnClick="btnContractResolverSetting_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnTraceWriterSetting" runat="server" Text="TraceWriter设置" OnClick="btnTraceWriterSetting_Click" />                        </td>                        <td>                            <asp:Button ID="btnErrorHandlingSetting" runat="server" Text="ErrorHandling设置" OnClick="btnErrorHandlingSetting_Click" /><br />                        </td>                    </tr>                    <tr>                        <td>                            <asp:Button ID="btnMaxDepthSetting" runat="server" Text="MaxDepth设置" OnClick="btnMaxDepthSetting_Click" />                        </td>                        <td>                            <br />                        </td>                    </tr>                </table>            </div>        </form>    </body></html>

DeserializeDemo.aspx.cs代码:

 public partial class DeserializeDemo : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {        }        protected void btnDeserializeAnObject_Click(object sender, EventArgs e)        {            string json = @"{               'Email': 'james@example.com',               'Active': true,               'CreatedDate': '2013-01-20T00:00:00Z',               'Roles': [                 'User',                 'Admin'               ]             }";            Account account = JsonConvert.DeserializeObject<Account>(json);            Response.Write(account.Email);        }        protected void btnDeserializeADictionary_Click(object sender, EventArgs e)        {            string json = @"{              'href': '/account/login.aspx',              'target': '_blank'            }";            Dictionary<string, string> htmlAttributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);            Response.Write(htmlAttributes["href"]);            // /account/login.aspx            Response.Write(htmlAttributes["target"]);        }        protected void btnDeserializeACollection_Click(object sender, EventArgs e)        {            string json = @"['Starcraft','Halo','Legend of Zelda']";            List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);            Response.Write(string.Join(", ", videogames.ToArray()));        }        protected void btnSerializeAnObject_Click(object sender, EventArgs e)        {        }        protected void btnDeserializeAnAnonymousType_Click(object sender, EventArgs e)        {            var definition = new {Name = ""};            string json1 = @"{'Name':'James'}";            var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);            Response.Write(customer1.Name);            // James            string json2 = @"{'Name':'Mike'}";            var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);            Response.Write(customer2.Name);        }        protected void btnDeserializeADataSet_Click(object sender, EventArgs e)        {            string json = @"{                'Table1': [                  {                    'id': 0,                    'item': 'item 0'                  },                  {                    'id': 1,                    'item': 'item 1'                  }                ]              }";            DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);            DataTable dataTable = dataSet.Tables["Table1"];            Response.Write(dataTable.Rows.Count);            // 2            foreach (DataRow row in dataTable.Rows)            {                Response.Write(row["id"] + " - " + row["item"]);            }        }        protected void btnWithCustomCreationConverter_Click(object sender, EventArgs e)        {            string json = @"{              'Department': 'Furniture',              'JobTitle': 'Carpenter',              'FirstName': 'John',              'LastName': 'Joinery',              'BirthDate': '1983-02-02T00:00:00'            }";            PersonModel person = JsonConvert.DeserializeObject<PersonModel>(json, new PersonConverter());            Response.Write(person.GetType().Name);            // Employee            EmployeeModel employee = (EmployeeModel) person;            Response.Write("<br />" + employee.JobTitle);        }        protected void btnDeserializeJSONFromAfile_Click(object sender, EventArgs e)        {            // read file into a string and deserialize JSON to a type            Movie movie1 = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(@"c:\movie.json"));            // deserialize JSON directly from a file            using (StreamReader file = File.OpenText(@"c:\movie.json"))            {                JsonSerializer serializer = new JsonSerializer();                Movie movie2 = (Movie) serializer.Deserialize(file, typeof (Movie));            }        }        protected void btnPopulateAnObject_Click(object sender, EventArgs e)        {            Account account = new Account            {                Email = "james@example.com",                Active = true,                CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),                Roles = new List<string>                {                    "User",                    "Admin"                }            };            string json = @"{             'Active': false,             'Roles': [               'Expired'             ]           }";            JsonConvert.PopulateObject(json, account);            Response.Write(account.Email);            Response.Write(account.Active);            Response.Write(string.Join(", ", account.Roles.ToArray()));        }        protected void btnConstructorHandlingSetting_Click(object sender, EventArgs e)        {            string json = @"{'Url':'http://www.google.com'}";            try            {                JsonConvert.DeserializeObject<Website>(json);            }            catch (Exception ex)            {                Response.Write(ex.Message);            }            Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings            {                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor            });            Response.Write(website.Url);        }        protected void btnObjectCreationHandlingSetting_Click(object sender, EventArgs e)        {            string json = @"{               'Name': 'James',               'Offices': [                 'Auckland',                 'Wellington',                 'Christchurch'               ]             }";            UserViewModel model1 = JsonConvert.DeserializeObject<UserViewModel>(json);            foreach (string office in model1.Offices)            {                Response.Write(office + "<br />");            }            UserViewModel model2 = JsonConvert.DeserializeObject<UserViewModel>(json, new JsonSerializerSettings            {                ObjectCreationHandling = ObjectCreationHandling.Replace            });            foreach (string office in model2.Offices)            {                Response.Write(office + "<br />");            }        }        protected void btnDefaultValueHandlingSetting_Click(object sender, EventArgs e)        {            Person person = new Person();            string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented);            Console.WriteLine(jsonIncludeDefaultValues);            // {            //   "Name": null,            //   "Age": 0,            //   "Partner": null,            //   "Salary": null            // }            string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented,                new JsonSerializerSettings                {                    DefaultValueHandling = DefaultValueHandling.Ignore                });            Response.Write(jsonIgnoreDefaultValues);        }        protected void btnMissingMemberHandlingSetting_Click(object sender, EventArgs e)        {            string json = @"{               'FullName': 'Dan Deleted',               'Deleted': true,               'DeletedDate': '2013-01-20T00:00:00'             }";            try            {                JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings                {                    MissingMemberHandling = MissingMemberHandling.Error                });            }            catch (JsonSerializationException ex)            {                Response.Write(ex.Message);                // Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.            }        }        protected void btnNullValueHandlingSetting_Click(object sender, EventArgs e)        {            Person person = new Person            {                Name = "Nigal Newborn",                Age = 1            };            string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);            Response.Write(jsonIncludeNullValues);            // {            //   "Name": "Nigal Newborn",            //   "Age": 1,            //   "Partner": null,            //   "Salary": null            // }            string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented,                new JsonSerializerSettings                {                    NullValueHandling = NullValueHandling.Ignore                });            Response.Write(jsonIgnoreNullValues);            // {            //   "Name": "Nigal Newborn",            //   "Age": 1            // }        }        protected void btnReferenceLoopHandlingSetting_Click(object sender, EventArgs e)        {            Employee joe = new Employee {Name = "Joe User"};            Employee mike = new Employee {Name = "Mike Manager"};            joe.Manager = mike;            mike.Manager = mike;            string json = JsonConvert.SerializeObject(joe, Formatting.Indented, new JsonSerializerSettings            {                ReferenceLoopHandling = ReferenceLoopHandling.Ignore            });            Response.Write(json);            // {            //   "Name": "Joe User",            //   "Manager": {            //     "Name": "Mike Manager"            //   }            // }        }        protected void btnDateFormatHandlingSetting_Click(object sender, EventArgs e)        {            DateTime mayanEndOfTheWorld = new DateTime(2012, 12, 21);            string jsonIsoDate = JsonConvert.SerializeObject(mayanEndOfTheWorld);            Response.Write(jsonIsoDate);            // "2012-12-21T00:00:00"            string jsonMsDate = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings            {                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat            });            Response.Write(jsonMsDate);            // "\/Date(1356044400000+0100)\/"        }        protected void btnDateTimeZoneHandlingSetting_Click(object sender, EventArgs e)        {            Flight flight = new Flight            {                Destination = "Dubai",                DepartureDate = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Unspecified),                DepartureDateUtc = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Utc),                DepartureDateLocal = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Local),                Duration = TimeSpan.FromHours(5.5)            };            string jsonWithRoundtripTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented,                new JsonSerializerSettings                {                    DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind                });            Response.Write(jsonWithRoundtripTimeZone);            // {            //   "Destination": "Dubai",            //   "DepartureDate": "2013-01-21T00:00:00",            //   "DepartureDateUtc": "2013-01-21T00:00:00Z",            //   "DepartureDateLocal": "2013-01-21T00:00:00+01:00",            //   "Duration": "05:30:00"            // }            string jsonWithLocalTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented,                new JsonSerializerSettings                {                    DateTimeZoneHandling = DateTimeZoneHandling.Local                });            Response.Write(jsonWithLocalTimeZone);            // {            //   "Destination": "Dubai",            //   "DepartureDate": "2013-01-21T00:00:00+01:00",            //   "DepartureDateUtc": "2013-01-21T01:00:00+01:00",            //   "DepartureDateLocal": "2013-01-21T00:00:00+01:00",            //   "Duration": "05:30:00"            // }            string jsonWithUtcTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented,                new JsonSerializerSettings                {                    DateTimeZoneHandling = DateTimeZoneHandling.Utc                });            Response.Write(jsonWithUtcTimeZone);            // {            //   "Destination": "Dubai",            //   "DepartureDate": "2013-01-21T00:00:00Z",            //   "DepartureDateUtc": "2013-01-21T00:00:00Z",            //   "DepartureDateLocal": "2013-01-20T23:00:00Z",            //   "Duration": "05:30:00"            // }            string jsonWithUnspecifiedTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented,                new JsonSerializerSettings                {                    DateTimeZoneHandling = DateTimeZoneHandling.Unspecified                });            Response.Write(jsonWithUnspecifiedTimeZone);            // {            //   "Destination": "Dubai",            //   "DepartureDate": "2013-01-21T00:00:00",            //   "DepartureDateUtc": "2013-01-21T00:00:00",            //   "DepartureDateLocal": "2013-01-21T00:00:00",            //   "Duration": "05:30:00"            // }        }        protected void btnTypeNameHandlingSetting_Click(object sender, EventArgs e)        {            Stockholder stockholder = new Stockholder            {                FullName = "Steve Stockholder",                Businesses = new List<Business>                {                    new Hotel                    {                        Name = "Hudson Hotel",                        Stars = 4                    }                }            };            string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented,                new JsonSerializerSettings                {                    TypeNameHandling = TypeNameHandling.All                });            Response.Write(jsonTypeNameAll);            // {            //   "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests",            //   "FullName": "Steve Stockholder",            //   "Businesses": {            //     "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib",            //     "$values": [            //       {            //         "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",            //         "Stars": 4,            //         "Name": "Hudson Hotel"            //       }            //     ]            //   }            // }            string jsonTypeNameAuto = JsonConvert.SerializeObject(stockholder, Formatting.Indented,                new JsonSerializerSettings                {                    TypeNameHandling = TypeNameHandling.Auto                });            Response.Write(jsonTypeNameAuto);            // {            //   "FullName": "Steve Stockholder",            //   "Businesses": [            //     {            //       "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",            //       "Stars": 4,            //       "Name": "Hudson Hotel"            //     }            //   ]            // }            // for security TypeNameHandling is required when deserializing            Stockholder newStockholder = JsonConvert.DeserializeObject<Stockholder>(jsonTypeNameAuto,                new JsonSerializerSettings                {                    TypeNameHandling = TypeNameHandling.Auto                });            Response.Write(newStockholder.Businesses[0].GetType().Name);            // Hotel        }        protected void btnMetadataPropertyHandlingSetting_Click(object sender, EventArgs e)        {            string json = @"{               'Name': 'James',               'Password': 'Password1',               '$type': 'MyNamespace.User, MyAssembly'             }";            object o = JsonConvert.DeserializeObject(json, new JsonSerializerSettings            {                TypeNameHandling = TypeNameHandling.All,                // $type no longer needs to be first                MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead            });            User u = (User) o;            Response.Write(u.Name);            // James        }        protected void btnContractResolverSetting_Click(object sender, EventArgs e)        {            PersonM person = new PersonM            {                FirstName = "Sarah",                LastName = "Security"            };            string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings            {                ContractResolver = new CamelCasePropertyNamesContractResolver()            });            Response.Write(json);            // {            //   "firstName": "Sarah",            //   "lastName": "Security",            //   "fullName": "Sarah Security"            // }        }        protected void btnTraceWriterSetting_Click(object sender, EventArgs e)        {            string json = @"{              'FullName': 'Dan Deleted',              'Deleted': true,              'DeletedDate': '2013-01-20T00:00:00'            }";            MemoryTraceWriter traceWriter = new MemoryTraceWriter();            Account account = JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings            {                TraceWriter = traceWriter            });            Response.Write(traceWriter.ToString());        }        protected void btnErrorHandlingSetting_Click(object sender, EventArgs e)        {            List<string> errors = new List<string>();            List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[              '2009-09-09T00:00:00Z',              'I am not a date and will error!',              [                1              ],              '1977-02-20T00:00:00Z',              null,              '2000-12-01T00:00:00Z'            ]",                new JsonSerializerSettings                {                    Error = delegate(object sd, Newtonsoft.Json.Serialization.ErrorEventArgs args)                    {                        errors.Add(args.ErrorContext.Error.Message);                        args.ErrorContext.Handled = true;                    },                    Converters = {new IsoDateTimeConverter()}                });        }        protected void btnMaxDepthSetting_Click(object sender, EventArgs e)        {            string json = @"[              [                [                  '1',                  'Two',                  'III'                ]              ]            ]";            try            {                JsonConvert.DeserializeObject<List<IList<IList<string>>>>(json, new JsonSerializerSettings                {                    MaxDepth = 2                });            }            catch (JsonReaderException ex)            {                Response.Write(ex.Message);                // The reader's MaxDepth of 2 has been exceeded. Path '[0][0]', line 3, position 12.            }        }        protected void btnPreserveReferencesHandlingSetting_Click(object sender, EventArgs e)        {            DirectoryModel root = new DirectoryModel {Name = "Root"};            DirectoryModel documents = new DirectoryModel {Name = "My Documents", Parent = root};            FileModel file = new FileModel {Name = "ImportantLegalDocument.docx", Parent = documents};            documents.Files = new List<FileModel> {file};            try            {                JsonConvert.SerializeObject(documents, Formatting.Indented);            }            catch (JsonSerializationException)            {            }            string preserveReferenacesAll = JsonConvert.SerializeObject(documents, Formatting.Indented,                new JsonSerializerSettings                {                    PreserveReferencesHandling = PreserveReferencesHandling.All                });            Response.Write(preserveReferenacesAll);            string preserveReferenacesObjects = JsonConvert.SerializeObject(documents, Formatting.Indented,                new JsonSerializerSettings                {                    PreserveReferencesHandling = PreserveReferencesHandling.Objects                });            Response.Write(preserveReferenacesObjects);        }    }    #region CustomCreationConverter    public class PersonModel    {        public string FirstName { get; set; }        public string LastName { get; set; }        public DateTime BirthDate { get; set; }    }    public class EmployeeModel : PersonModel    {        public string Department { get; set; }        public string JobTitle { get; set; }    }    public class PersonConverter : CustomCreationConverter<PersonModel>    {        public override PersonModel Create(Type objectType)        {            return new EmployeeModel();        }    }    #endregion    #region  ObjectCreationHandlingSetting所需要的实体类    public class UserViewModel    {        public string Name { get; set; }        public IList<string> Offices { get; private set; }        public UserViewModel()        {            Offices = new List<string>            {                "Auckland",                "Wellington",                "Christchurch"            };        }    }    #endregion    #region TypeNameHandling所需要的实体类    public abstract class Business    {        public string Name { get; set; }    }    public class Hotel : Business    {        public int Stars { get; set; }    }    public class Stockholder    {        public string FullName { get; set; }        public IList<Business> Businesses { get; set; }    }    #endregion    #region ContractResolver所需要的实体类    public class PersonM    {        public string FirstName { get; set; }        public string LastName { get; set; }        public string FullName        {            get { return FirstName + " " + LastName; }        }    }    #endregion    #region TraceWriterSetting所需要的实体类    public class AccountModel    {        public string FullName { get; set; }        public bool Deleted { get; set; }    }    #endregion    #region PreserveReferencesHandlingSetting所需要的实体类    public class DirectoryModel    {        public string Name { get; set; }        public DirectoryModel Parent { get; set; }        public IList<FileModel> Files { get; set; }    }    public class FileModel    {        public string Name { get; set; }        public DirectoryModel Parent { get; set; }    }    #endregion

运行结果如图:

这里写图片描述

0 0
原创粉丝点击