• C# JSON 序列化


    1、JavaScriptSerializer

    System.Web.Extensions.dll

    System.Web.Script.Serialization命名空间

    Serialize

     Deserialize

    http://www.cnblogs.com/dwfbenben/archive/2013/06/06/3122662.html

     http://www.cnblogs.com/xiaolifeidao/archive/2013/01/28/2879523.html

    2、Newtonsoft

    http://www.newtonsoft.com/json

    download 添加引用  :Newtonsoft.Json.dll

    http://www.cnblogs.com/yanweidie/p/4605212.html

     JsonConvert

    数组序列化

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
            private void button1_Click(object sender, EventArgs e)
            {
    
                string str;
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("id", "0002");
                dic.Add("name", "kitty");
                //数组、对象序列化成字符串
                str = JsonConvert.SerializeObject(dic);
                this.richTextBox1.Text = str;
                //{"id":"0002","name":"kitty"}
    
                //反序列化成对象、数组
                var aobj= JsonConvert.DeserializeObject<Dictionary<string,string>>(str);
                this.Text = aobj["id"].ToString().Trim();
                this.Text = aobj["name"];
            }

    类序列化 JsonConvert与JavaScriptSerializer结果相同。JsonConvert把对象序列化成json串,用JavaScriptSerializer反序列化也是可以的

     public class Person
            {
                public Person()
                { }
                public Person(int id, string name, int age)
                {
                    this.Id = id;
                    this.Name = name;
                    this.Age = age;
                }
                public int Id { get; set; }
                public string Name { get; set; }
                public int Age { get; set; }
            }
      
        
    JavaScriptSerializer 
            private void button2_Click(object sender, EventArgs e)
            {            
                JavaScriptSerializer jss = new JavaScriptSerializer();
                Person  pp=new Person(01,"kitty",28);
    
                //对象序列化为json字符串
                this.richTextBox1.Text= jss.Serialize(pp);
    
    
                //json串反序列化为对象
                Person p2 = jss.Deserialize<Person>(this.richTextBox1.Text);
                this.Text = p2.Id.ToString();
            }

     JsonConvert

            private void button3_Click(object sender, EventArgs e)
            {
                Person pp = new Person(01, "kitty", 28);
                this.richTextBox1.Text =JsonConvert.SerializeObject(pp);
    
                Person p2 = JsonConvert.DeserializeObject<Person>(this.richTextBox1.Text);
                this.Text = p2.Name;
                
            }

    datatable序列化为json串

    方法1简单

                DataTable dt = new DataTable();
                dt.Columns.Add("id");
                dt.Columns.Add("name");
                dt.Rows.Add(1, "aaa");
                dt.Rows.Add(2, "bbb");
                dt.Rows.Add(3, "ccc");
                dt.Rows.Add(4, "eee");
                 
    //dataTable序列化为json字符串
    this.richTextBox1.Text = JsonConvert.SerializeObject(dt);
    //json串反序列化为dataTable
    var dtnew = JsonConvert.DeserializeObject<DataTable>(richTextBox1.Text); this.Text = dtnew.Rows.Count.ToString();

     [{"id":"1","name":"aaa"},{"id":"2","name":"bbb"},{"id":"3","name":"ccc"},{"id":"4","name":"eee"}]

     Newtonsoft.Json.JsonConvert.SerializeObject

    方法二

            private void button5_Click(object sender, EventArgs e)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("id");
                dt.Columns.Add("name");
                dt.Rows.Add(1, "aaa");
                dt.Rows.Add(2, "bbb");
                dt.Rows.Add(3, "ccc");
                dt.Rows.Add(4, "eee");
    
                JavaScriptSerializer jss = new JavaScriptSerializer();
                jss.RegisterConverters(new JavaScriptConverter[]{new DataTableConverter()});
                this.richTextBox1.Text = jss.Serialize(dt);
    
            }
    
    
    
      public class DataTableConverter : JavaScriptConverter
        {
            public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
            {
                DataTable dt = obj as DataTable;
                Dictionary<string, object> result = new Dictionary<string, object>();
    
                List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    
                foreach (DataRow dr in dt.Rows)
                {
                    Dictionary<string, object> row = new Dictionary<string, object>();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        row.Add(dc.ColumnName, dr[dc.ColumnName]);
                    }
                    rows.Add(row);
                }
    
                result["Rows"] = rows;
    
                return result;
            }
    
            public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                throw new NotImplementedException();
            }
    
            /// <summary>
            /// 获取本转换器支持的类型
            /// </summary>
            public override IEnumerable<Type> SupportedTypes
            {
                get { return new Type[] { typeof(DataTable) }; }
            }
        }

    .net 4.5

    JsonReader reader = new JsonReader(new StringReader(jsonText));  

    error,无法创建抽象类或接口“Newtonsoft.Json.JsonWriter”的实例

    like this ok:

     写json

    WriteStartArray、WriteStartObject,与end WriteEndObject成对出现。
    StringWriter sw = new StringWriter();
                JsonWriter writer = new JsonTextWriter(sw);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartObject();
                writer.WritePropertyName("myparams");
                writer.WriteStartObject();
                writer.WritePropertyName("id");
                writer.WriteValue("0001");
                writer.WritePropertyName("name");
                writer.WriteValue("kitty");
                writer.WritePropertyName("age");
                writer.WriteValue(99);
                writer.WriteEndObject();
                writer.WriteEndObject();
                writer.Flush();
                sw.Close();
                this.richTextBox1.Text = sw.GetStringBuilder().ToString();

    解析读json

    Newtonsoft.Json.JsonReader reader = new JsonTextReader(new StringReader(this.richTextBox1.Text));
                while (reader.Read())
                {
                    this.listBox1.Items.Add(reader.TokenType);
                }
  • 相关阅读:
    领会一些比较巧妙的算法
    操作系统os常识
    C++中的继承与虚函数各种概念
    我学shell程序的记录
    matlab:linux环境中将m文件编译成动态链接库
    struct内存对齐:gcc与VC的差别
    fedora中丢失或损坏fstab,无法启动,如何补救
    判断一个字符串中的字符是否都在另一个中出现
    linux下的不错的小软件:apvlv,zathura和vifm
    C语言中将结构体写入文件
  • 原文地址:https://www.cnblogs.com/cb168/p/5327104.html
Copyright © 2020-2023  润新知