Json.NET 基本使用教程

/*
 * 由SharpDevelop创建。
 * 用户: Changweihua
 * 日期: 2013/11/4
 * 时间: 14:06
 *
 * changweihua@outlook.com
 * http://www.cmono.net
 *
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Globalization;
using System.Dynamic;
using System.Reflection;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace JsonNetSample
{
    class Program
    {
        public static void Main(string[] args)
        {
            var list = PersonRepository.GetPersons();
//          Console.WriteLine(JsonConvert.SerializeObject(list, Formatting.Indented));
               
            JsonSerializer serializer = new JsonSerializer();
            StringBuilder sb = new StringBuilder(0x100);
            using(StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture))
            {
                using (JsonTextWriter writer = new JsonTextWriter(sw))
                {
                    writer.Formatting = Formatting.Indented;
                    serializer.Serialize(writer, list);
                }
            }
               
//          Console.WriteLine(sb.ToString());
               
            MyArray ma = new MyArray{ Name = "myArray" };
            ma.Add(1);
            ma.Add(2);
            ma.Add("3");
               
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Formatting = Formatting.Indented;
            settings.DefaultValueHandling = DefaultValueHandling.Ignore;
               
            Console.WriteLine(JsonConvert.SerializeObject(ma, settings));
               
            Staff changweihua = new Staff{ Name = "Chang Weihua", Birthday = new DateTime(1991,2,9), EmploymentDate = new DateTime(2013,8,12), Today = DateTime.Now };
//          IsoDateTimeConverter converter = new IsoDateTimeConverter{ DateTimeFormat = "yyyy'年'MM'月'dd'日'" };
//          settings.Converters.Add(converter);
            settings.DateFormatString = "yyyy'年'MM'月'dd'日'";
            Console.WriteLine(JsonConvert.SerializeObject(changweihua, settings));
               
            dynamic d = new MyDynamic();
            //必须添加 Microsoft.CSharp 程序集引用,在 GAC 中
            d.Name = "Chang Weihua";
               
            Action<string> print = new Action<string>((value) => { Console.WriteLine(value); });
            d.Print = print;
            Console.WriteLine(JsonConvert.SerializeObject(d, Formatting.Indented));
                   
            DataTable dt = new DataTable();
            DataColumn column1 = new DataColumn("Name");
            DataColumn column2 = new DataColumn("Age", typeof(int));
            DataColumn column3 = new DataColumn("City");
               
            dt.Columns.AddRange(new DataColumn[]{column1, column2, column3});
               
            DataRow row = null;
               
            for (int i = 0; i < 10; i++)
            {
                row = dt.NewRow();
                row["Name"] = "Name" + i;
                row[1] = i;
                row["City"] = "City" + i;
                dt.Rows.Add(row);
            }
               
            var dtString = JsonConvert.SerializeObject(dt, Formatting.Indented);
               
            Console.WriteLine(dtString);
               
            DataTable table = JsonConvert.DeserializeObject<DataTable>(dtString);
               
            for (int i = 0; i < table.Rows.Count; i++)
            {
                row = table.Rows[i];
                Console.WriteLine("{0}\t{1}\t{2}", row[0], row[1], row[2]);
            }
               
               
            Console.ReadKey(true);
        }
    }
       
    /// <summary>
    /// 序列化自定义类型, 必须加上 JsonObjectAttribute, 默认是 JsonArrayAttribute
    /// Newtonsoft.Json.MemberSerialization.OptIn 默认值,类中所有公有成员会被序列化,如果不想被序列化,可以用特性JsonIgnore
    /// Newtonsoft.Json.MemberSerialization.OptOut 默认情况下,所有的成员不会被序列化,类中的成员只有标有特性JsonProperty的才会被序列化,当类的成员很多,但客户端仅仅需要一部分数据时,很有用
    /// Json.Net序列化对象时,默认情况下仅仅序列化公有成员,如果想要非公有成员也被序列化,就要在该成员上加特性"JsonProperty"
    /// </summary>
    [JsonObject(MemberSerialization.OptIn)]
    class MyArray : ArrayList
    {
        [JsonProperty]
        public string Name { get; set; }
           
        [JsonProperty]
        int id = 1;
    }
       
    class PersonRepository
    {
        public static IEnumerable<Person> GetPersons()
        {
            List<Person> list = new List<Person>();
               
            list.Add(new Person{ Name = "Tom", Age = 32, Gender = Gender.Male, Email = "tom@cmono.net"});
            list.Add(new Person{ Name = "Jack", Age = 23, Gender = Gender.Male, Email = "jack@cmono.net"});
            list.Add(new Person{ Name = "Eden", Age = 25, Gender = Gender.Female, Email = "enden@cmono.net"});
            list.Add(new Person{ Name = "Li Hua", Age = 29, Gender = Gender.Male, Email = "lihua@cmono.net"});
            list.Add(new Person{ Name = "Lvo", Age = 18, Gender = Gender.Female, Email = "lvo@cmono.net"});
               
            return list;
        }
    }
       
    enum Gender
    {
        Male = 5,
        Female
    }
       
    class Person
    {
        public string Name{get;set;}
        public int Age{get;set;}
        public Gender Gender{get;set;}
        public string Email{get;set;}
        public bool IsDeleted{get;set;}
    }
       
    class Staff
    {
        [JsonProperty(PropertyName = "StaffName")]//更改格式化之后的名称
        public string Name { get; set; }
        [JsonConverter(typeof(IsoDateTimeConverter))]
        public DateTime Birthday { get;set; }
        [JsonConverter(typeof(JavaScriptDateTimeConverter))]
        public DateTime EmploymentDate { get; set;}
        public DateTime Today { get;set; }
    }
       
       
    class MyDynamic : DynamicObject
    {
        /// <summary>
        /// 用来存储动态添加变量和值
        /// </summary>
        private Dictionary<string, object> members = new Dictionary<string, object>();
           
        /// <summary>
        /// 获取所以动态成员名称
        /// </summary>
        /// <returns></returns>
        public override IEnumerable<string> GetDynamicMemberNames()
        {
//          return members.Keys;
            foreach (string key in members.Keys)//排除 Delegate 类型
            {
                if(!(members[key] is Delegate))
                    yield return key;
            }
        }
           
        /// <summary>
        /// 设置动态成员名称,赋值
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if(!members.ContainsKey(binder.Name))
            {
                members.Add(binder.Name, value);
            }
            else
            {
                members[binder.Name] = value;
            }
            Console.WriteLine(binder.Name + " 属性被设置," + "设置的值为: " + value);
            return true;
        }
           
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if(members.ContainsKey(binder.Name))
            {
                result = members[binder.Name];
                return true;
            }
            return base.TryGetMember(binder, out result);
        }
           
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            if(members.ContainsKey(binder.Name) && members[binder.Name] is Delegate)
            {
                result = (members[binder.Name] as Delegate).DynamicInvoke(args);
                return true;
            }
            else
            {
                return base.TryInvokeMember(binder, args, out result);
            }
        }
           
    }
       
}


知识共享许可协议
《Json.NET 基本使用教程》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     150.77ms