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

前端之家收集整理的这篇文章主要介绍了Json.NET使用入门(一)【序列化】前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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


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);
        }
    }

运行结果如图:

原文链接:https://www.f2er.com/json/289171.html

猜你在找的Json相关文章