加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 18:54:02 所属栏目:百科 来源:网络整理
导读:不要失去希望,你永远不知道明天会带来什么。很多事犹如天气,慢慢热或者渐渐冷,等到惊悟,已过了一季。趁年青,趁梦想还在,想去的地方,现在就去。想做的事情,现在就做。 Model层的实体类: public class Account { public string Email { get ; set ; }

不要失去希望,你永远不知道明天会带来什么。很多事犹如天气,慢慢热或者渐渐冷,等到惊悟,已过了一季。趁年青,趁梦想还在,想去的地方,现在就去。想做的事情,现在就做。


Model层的实体类:

public class Account
    {
        public string Email { get; set; }
        public bool Active { get; set; }
        public DateTime CreatedDate { get; set; }
        public IList<string> Roles { get; set; }
    }
public class Employee
   {
       public string Name { get; set; }
       public Employee Manager { get; set; }

       public bool ShouldSerializeManager()
       { 
           return (Manager != this);
       }
   }
public class JavaScriptSettings
   {
       public JRaw OnLoadFunction { get; set; }
       public JRaw OnUnloadFunction { get; set; }
   }
public class Movie
    {
        public string Name { get; set; }
        public int Year { get; set; }
    }

Default.aspx内容:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="NewtonsoftDemo.Default" %>

<!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="btnSerializeAnObject" runat="server" Text="序列化一个对象" OnClick="btnSerializeAnObject_Click" />
                    </td>
                    <td>
                        <asp:Button ID="btnSerializeACollection" runat="server" Text="序列化集合" OnClick="btnSerializeACollection_Click" /><br />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnSerializeADictionary" runat="server" Text="序列化一个字典" OnClick="btnSerializeADictionary_Click" />
                    </td>
                    <td>
                        <asp:Button ID="btnSerializeJSONToFile" runat="server" Text="序列JSON到文件" OnClick="btnSerializeJSONToFile_Click" /><br />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnSerializeWithJsonConverters" runat="server" Text="用JsonConverters序列化" OnClick="btnSerializeWithJsonConverters_Click" />
                    </td>
                    <td>
                        <asp:Button ID="btnSerializeADataSet" runat="server" Text="序列化一个DataSet" OnClick="btnSerializeADataSet_Click" Style="height: 21px" /><br />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnSerializeRawJSON" runat="server" Text="序列化原始JSON值" OnClick="btnSerializeRawJSON_Click" />
                    </td>
                    <td>
                        <asp:Button ID="btnSerializeUnindentedJSON" runat="server" Text="序列化不缩进JSON" OnClick="btnSerializeUnindentedJSON_Click" /><br />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnSerializeConditionalProperty" runat="server" Text="序列化条件属性" OnClick="btnSerializeConditionalProperty_Click" /></td>
                    <td>
                        <br />
                    </td>
                </tr> 
            </table>

        </div>
    </form>
</body>
</html>

Default.aspx.cs代码:

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender,EventArgs e)
        {
        }

        protected void btnSerializeAnObject_Click(object sender,EventArgs e)
        {
            Account account = new Account
            {
                Email = "james@example.com",Active = true,CreatedDate = new DateTime(2013,1,20,0,DateTimeKind.Utc),Roles = new List<string>
                {
                    "User","Admin"
                }
            };

            string json = JsonConvert.SerializeObject(account,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnSerializeACollection_Click(object sender,EventArgs e)
        {
            List<string> videogames = new List<string>
            {
                "Starcraft","Halo","Legend of Zelda"
            };

            string json = JsonConvert.SerializeObject(videogames);

            Response.Write(json);
        }

        protected void btnSerializeADictionary_Click(object sender,EventArgs e)
        {
            Dictionary<string,int> points = new Dictionary<string,int>
            {
                {"James",9001},{"Jo",3474},{"Jess",11926}
            };

            string json = JsonConvert.SerializeObject(points,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnSerializeJSONToFile_Click(object sender,EventArgs e)
        {
            Movie movie = new Movie
            {
                Name = "Bad Boys",Year = 1995
            };

            //JSON序列化到一个字符串,然后写入字符串到文件
            File.WriteAllText(Server.MapPath("~/App_Data/movie.json"),JsonConvert.SerializeObject(movie));

            //直接序列JSON到文件
            using (StreamWriter file = File.CreateText(Server.MapPath("~/App_Data/movie.json")))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file,movie);
            }
        }

        protected void btnSerializeWithJsonConverters_Click(object sender,EventArgs e)
        {
            List<StringComparison> stringComparisons = new List<StringComparison>
            {
                StringComparison.CurrentCulture,StringComparison.Ordinal
            };

            string jsonWithoutConverter = JsonConvert.SerializeObject(stringComparisons);

            Response.Write(jsonWithoutConverter);

            string jsonWithConverter = JsonConvert.SerializeObject(stringComparisons,new StringEnumConverter());

            Response.Write(jsonWithConverter);


            List<StringComparison> newStringComparsions =
                JsonConvert.DeserializeObject<List<StringComparison>>(jsonWithConverter,new StringEnumConverter());

            Response.Write(string.Join(",",newStringComparsions.Select(c => c.ToString()).ToArray()));

        }

        protected void btnSerializeADataSet_Click(object sender,EventArgs e)
        {
            DataSet dataSet = new DataSet("dataSet");
            dataSet.Namespace = "NetFrameWork";
            DataTable table = new DataTable();
            DataColumn idColumn = new DataColumn("id",typeof (int));
            idColumn.AutoIncrement = true;

            DataColumn itemColumn = new DataColumn("item");
            table.Columns.Add(idColumn);
            table.Columns.Add(itemColumn);
            dataSet.Tables.Add(table);

            for (int i = 0; i < 2; i++)
            {
                DataRow newRow = table.NewRow();
                newRow["item"] = "item " + i;
                table.Rows.Add(newRow);
            }

            dataSet.AcceptChanges();

            string json = JsonConvert.SerializeObject(dataSet,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnSerializeRawJSON_Click(object sender,EventArgs e)
        {
            JavaScriptSettings settings = new JavaScriptSettings
            {
                OnLoadFunction = new JRaw("OnLoad"),OnUnloadFunction = new JRaw("function(e) { alert(e); }")
            };

            string json = JsonConvert.SerializeObject(settings,Formatting.Indented);

            Response.Write(json);
        }

        protected void btnSerializeUnindentedJSON_Click(object sender,EventArgs e)
        {
            Account account = new Account
           {
               Email = "james@example.com",Roles = new List<string>
               {
                   "User","Admin"
               }
           };

           string json = JsonConvert.SerializeObject(account);

           Response.Write(json);
        }

        protected void btnSerializeConditionalProperty_Click(object sender,EventArgs e)
        {
            Employee joe = new Employee();
            joe.Name = "Joe Employee";
            Employee mike = new Employee();
            mike.Name = "Mike Manager";

            joe.Manager = mike; 
            mike.Manager = mike;

            string json = JsonConvert.SerializeObject(new[] { joe,mike },Formatting.Indented);

            Response.Write(json);
        }
    }

运行结果如图:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读