• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#JSON序列化

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#分析搜索引擎url得到搜索关键字发布时间:2022-07-13
下一篇:
C#SqlHelper发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap