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

本文介绍了使用C#进行JSON序列化的多种方法,包括序列化对象、集合、字典等,并展示了如何处理特殊类型的序列化需求,如序列化条件属性等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


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, 0, 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",
               Active = true,
               CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
               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);
        }
    }

运行结果如图:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值