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", "");
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(,"kitty",); //对象序列化为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(, "kitty", );
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(, "aaa");
dt.Rows.Add(, "bbb");
dt.Rows.Add(, "ccc");
dt.Rows.Add(, "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(, "aaa");
dt.Rows.Add(, "bbb");
dt.Rows.Add(, "ccc");
dt.Rows.Add(, "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("");
writer.WritePropertyName("name");
writer.WriteValue("kitty");
writer.WritePropertyName("age");
writer.WriteValue();
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);
}
C# JSON 序列化的更多相关文章
- .Net深入实战系列—JSON序列化那点事儿
序 当前主流的序列化JSON字符串主要有两种方式:JavaScriptSerializer及Json.net(Nuget标识:Newtonsoft.Json).JavaScriptSerializer ...
- Newtonsoft.Json 序列化和反序列化 时间格式【转】
1.JSON序列化 string JsonStr= JsonConvert.SerializeObject(Entity); eg: A a=new A(); a.Name="Elain ...
- [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类
[.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类 本节导读: 关于JSON序列化,不能 ...
- DotNet的JSON序列化与反序列化
JSON(JavaScript Object Notation)JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式.在现在的通信中,较多的采用JSON数据格式,JSON有 ...
- C#中JSON序列化和反序列化
有一段时间没有到博客园写技术博客了,不过每天逛逛博客园中大牛的博客还是有的,学无止境…… 最近在写些调用他人接口的程序,用到了大量的JSON.XML序列化和反序列化,今天就来总结下json的序列化和反 ...
- 使用JSON.Net(Newtonsoft.Json)作为ASP.Net MVC的json序列化和反序列化工具
ASP.Net MVC默认的JSON序列化使用的是微软自己的JavaScriptSerializer.性能低不说,最让人受不了的是Dictionary<,>和Hashtable类型居然对应 ...
- Windows Phone 六、JSON序列化
JSON序列化 public class Person { public int Id { get; set; } public string Name { get; set; } public in ...
- [MVC_Json序列化]MVC之Json序列化循环引用
在做MVC项目时,难免会遇到Json序列化循环引用的问题,大致错误如下 错误1:序列化类型为“...”的对象时检测到循环引用. 错误2:Self referencing loop detected f ...
- NetworkComms V3 使用Json序列化器进行网络通信
刚才在网上闲逛,偶然看到一篇文章 C#(服务器)与Java(客户端)通过Socket传递对象 网址是:http://www.cnblogs.com/iyangyuan/archive/2012/12/ ...
- json序列化时datetime的处理方法
.net自带的json序列化器,JavaScriptSerializer和DataContractJsonSerializer,都是序列化成微软的datetime json格式,e.g. " ...
随机推荐
- web sql 基本操作 - 增删改查
不喜欢看md原文的 可以访问这个链接:http://note.youdao.com/noteshare?id=6a91e3dea7cdf5195bb0e851d9fcb5a5 # web sql 增删 ...
- 玲珑杯 round18 A 计算几何瞎暴力
题目链接 : http://www.ifrog.cc/acm/problem/1143 当时没看到坐标的数据范围= =看到讨论才意识到,不同的坐标最多只有1k多个,完全可以暴力做法,不过也要一些技巧. ...
- HDU 4004 二分
The Frog's Games Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Others) ...
- IOS-网络(大文件下载)
一.不合理方式 // // ViewController.m // IOS_0131_大文件下载 // // Created by ma c on 16/1/31. // Copyright © 20 ...
- 集成学习之Boosting —— AdaBoost实现
集成学习之Boosting -- AdaBoost原理 集成学习之Boosting -- AdaBoost实现 AdaBoost的一般算法流程 输入: 训练数据集 \(T = \left \{(x_1 ...
- L205 EE
As an Electrical Engineer at P, you will: Design, build, and verify PCBAsCreate, modify, and update ...
- json to xml
/* This work is licensed under Creative Commons GNU LGPL License. License: http://creativecommons.or ...
- C# 空合并操作符(??)不可重载?其实有黑科技可以间接重载!
?? 操作符叫做 null-coalescing operator,即 null 合并运算符.如果此运算符的左操作数不为 null,则此运算符将返回左操作数:否则返回右操作数. 在微软的官方 C# 文 ...
- WCF WS-Security and WSE Nonce Authentication【转】
原文:http://weblog.west-wind.com/posts/2012/Nov/24/WCF-WSSecurity-and-WSE-Nonce-Authentication?utm_sou ...
- 使用mongoperf评估磁盘随机IO性能
用法举例: # 16个io线程 # 随机读写10GB的测试文件 echo "{nThreads:16,fileSizeMB:10000,r:true,w:true}" | mong ...