c#操作json示例分享
1..net对json的支持介绍
(1)操作json的dll介绍
.net自身有system.runtime.serialization.dll与system.web.extensions.dll,使用这两个dll可以把对象序列化和反序列化成json数据。也可以使用第三方的newtonsoft.json.dll来操作json数据,使用它会更方便的操作json数据,其功能也跟强一些。
(2)使用system.web.extensions.dll的限制
要使用system.web.extensions.dll必须是在web项目中,只有在web项目中才能引用此dll。
2.json序列化和反序列化
(1)使用newtonsoft.json.dll实现
代码示例:
public class person
{
public string name;//姓名
public bool sex;//性别,是否是男
public person(string name, bool sex)
{
this.name = name;
this.sex = sex;
}
public override string tostring()
{
return "姓名:" + this.name + "\t性别:" + (this.sex ? "男" : "女");
}
}
public class programmer : person
{
public list<string> languages;//编程语言
public programmer(string name, bool sex, list<string> languages) : base(name, sex)
{
this.languages = languages;
}
public override string tostring()
{
stringbuilder str = new stringbuilder();
str.append(base.tostring() + "\t编程语言:");
foreach (string l in this.languages)
{
str.append(l + " ");
}
return str.tostring();
}
}
class program
{
static void main(string[] args)
{
string filepath = @"d:\users\lizw\桌面\objectjson.txt";
list<string> languages = null;
list<programmer> list = new list<programmer>();
languages = new list<string>(new string[] { "c#", "java" });
list.add(new programmer("*伟", true, languages));
languages = new list<string>(new string[] { "c#", "c++" });
list.add(new programmer("coder2", false, languages));
languages = new list<string>(new string[] { "c#", "c++", "c", "java" });
list.add(new programmer("coder3", true, languages));
//序列化对象
string jsonstr = jsonconvert.serializeobject(list);//将对象转换成json存储
file.writealltext(filepath, jsonstr);
list.clear();
//反序列化对象
list = jsonconvert.deserializeobject<list<programmer>>(jsonstr);
foreach (programmer p in list)
{
console.writeline(p);
}
console.writeline("ok!");
console.read();
}
}
得到的json文本:
[{"languages":["c#","java"],"name":"*伟","sex":true},
{"languages":["c#","c++"],"name":"coder2","sex":false},
{"languages":["c#","c++","c","java"],"name":"coder3","sex":true}]
注意:此种方式json序列化对象时,只能序列化对象的公有成员。
(2)使用system.web.extensions.dll实现
代码示例:
public class person
{
public string name;//姓名
public bool sex;//性别,是否是男
public person() { }//必须有此构造方法,否者无法反序列化
public person(string name, bool sex)
{
this.name = name;
this.sex = sex;
}
public override string tostring()
{
return "姓名:" + this.name + "\t性别:" + (this.sex ? "男" : "女");
}
}
public class programmer : person
{
public list<string> languages;//编程语言
public programmer() { }//必须有此构造方法,否者无法反序列化
public programmer(string name, bool sex, list<string> languages)
: base(name, sex)
{
this.languages = languages;
}
public override string tostring()
{
stringbuilder str = new stringbuilder();
str.append(base.tostring() + "\t编程语言:");
foreach (string l in this.languages)
{
str.append(l + " ");
}
return str.tostring();
}
}
public partial class webform1 : system.web.ui.page
{
protected void page_load(object sender, eventargs e)//web页面的加载事件
{
list<string> languages = null;
list<programmer> list = new list<programmer>();
languages = new list<string>(new string[] { "c#", "java" });
list.add(new programmer("*伟", true, languages));
languages = new list<string>(new string[] { "c#", "c++" });
list.add(new programmer("coder2", false, languages));
languages = new list<string>(new string[] { "c#", "c++", "c", "java" });
list.add(new programmer("coder3", true, languages));
//序列化对象
javascriptserializer jsonserialize = new javascriptserializer();
string jsonstr = jsonserialize.serialize(list);//将对象转换成json存储
response.write(jsonstr + "<br>");//前台输出
//反序列化对象
list.clear();
list = jsonserialize.deserialize<list<programmer>>(jsonstr);
foreach (programmer p in list)
{
response.write(p + "<br>");//前台输出
}
}
}
得到的json文本:
[{"languages":["c#","java"],"name":"*伟","sex":true},
{"languages":["c#","c++"],"name":"coder2","sex":false},
{"languages":["c#","c++","c","java"],"name":"coder3","sex":true}]
注意:此种方式json序列化对象时,除了只能序列化对象的公有成员外,被序列化的对象还必须有无参的构造方法才能被反序列化!system.web.extensions.dll只能在web项目中引用,在控制台和winfrom项目中无法引用!
(3)使用system.runtime.serialization.dll实现
代码示例:
[datacontract]//必须申明,否则无法序列化
public class person
{
[datamember(name = "姓名")]//必须申明,否则无法序列化
private string name;
[datamember(name = "性别")]//必须申明,否则无法序列化
private bool sex;
public person(string name, bool sex)
{
this.name = name;
this.sex = sex;
}
public override string tostring()
{
return "姓名:" + this.name + "\t性别:" + (this.sex ? "男" : "女");
}
}
[datacontract]
public class programmer : person
{
[datamember(name = "编程语言")]
private list<string> languages;
public programmer(string name, bool sex, list<string> languages)
: base(name, sex)
{
this.languages = languages;
}
public override string tostring()
{
stringbuilder str = new stringbuilder();
str.append(base.tostring() + "\t编程语言:");
foreach (string l in this.languages)
{
str.append(l + " ");
}
return str.tostring();
}
}
class program
{
static void main(string[] args)
{
string filepath = @"d:\users\lizw\桌面\objectjson.txt";
list<string> languages = null;
list<programmer> list = new list<programmer>();
languages = new list<string>(new string[] { "c#", "java" });
list.add(new programmer("*伟", true, languages));
languages = new list<string>(new string[] { "c#", "c++" });
list.add(new programmer("coder2", false, languages));
languages = new list<string>(new string[] { "c#", "c++", "c", "java" });
list.add(new programmer("coder3", true, languages));
//序列化对象
datacontractjsonserializer ser =
new datacontractjsonserializer(typeof(list<programmer>));
memorystream ms = new memorystream();
ser.writeobject(ms, list);//将对象转换成json存储
string jsonstr = encoding.utf8.getstring(ms.toarray());
file.writealltext(filepath, jsonstr);
//反序列化对象
list.clear();
ms.position = 0;
list = (list<programmer>)ser.readobject(ms);
foreach (programmer p in list)
{
console.writeline(p);
}
ms.dispose();//关闭内存流
console.writeline("ok!");
console.read();
}
}
[code]
得到的json文本:
[{"姓名":"*伟","性别":true,"编程语言":["c#","java"]},
{"姓名":"coder2","性别":false,"编程语言":["c#","c++"]},
{"姓名":"coder3","性别":true,"编程语言":["c#","c++","c","java"]}]
注意:此种方式json序列化对象时,可以序列化对象的任意成员(包括私有成员),但是使用此方式必须要在类和成员的定义处加上相应的特性(具体请参考代码)。
(4)小结
3.解析json字符串(使用newtonsoft.json.dll)
(1)使用jsontextreader类进行只进读取(不常用)
[code]
class program
{
static void main(string[] args)
{
//json字符串
string jsonstr = @"
[{'languages':['c#','java'],'name':'*伟','sex':true},
{'languages':['c#','c++'],'name':'coder2','sex':false},
{'languages':['c#','c++','c','java'],'name':'coder3','sex':true}]";
jsontextreader json = new jsontextreader(new stringreader(jsonstr));
while (json.read())
{
console.writeline(json.value + "--" + json.tokentype + "--" + json.valuetype);
}
console.writeline("ok!");
console.read();
}
}
(2)使用jarray、jobject、jtoken进行读取(常用)
class program
{
static void main(string[] args)
{
//json字符串
string jsonstr = @"
[{'languages':['c#','java'],'name':'*伟','sex':true},
{'languages':['c#','c++'],'name':'coder2','sex':false},
{'languages':['c#','c++','c','java'],'name':'coder3','sex':true}]";
jarray ja = (jarray)jsonconvert.deserializeobject(jsonstr);
foreach (jtoken jt in ja)
{
jobject jo = (jobject)jt;
jarray temp = (jarray)jo["languages"];
foreach (jtoken token in temp)
{
console.write(token+" ");
}
console.writeline("\t" + jo["name"] + "\t" + jo["sex"]);
}
console.writeline("ok!");
console.read();
}
}
(3)json时间字符串的处理
class program
{
static void main(string[] args)
{
datetime time = datetime.now;
//这里使用自定义日期格式
isodatetimeconverter timeconverter = new isodatetimeconverter();
timeconverter.datetimeformat = "北京时间:yyyy-mm-dd hh:mm:ss";
//序列化时间
string jsonstr = jsonconvert.serializeobject(time, timeconverter);
console.writeline(jsonstr);
//反序列化时间
datetime time2 = jsonconvert.deserializeobject<datetime>(jsonstr, timeconverter);
console.writeline(time2);
console.writeline("ok!");
console.read();
}
}
4.读取json字符串的技巧
(1)使用匿名类
class program
{
static void main(string[] args)
{
//json字符串
string jsonstr = @"{'languages':['c#','java'],'name':'*伟','sex':true}";
//创建匿名类
var tempclass = new { languages = new string[0], name = string.empty, sex = false };
//反序列化
var o = jsonconvert.deserializeanonymoustype(jsonstr, tempclass);
console.writeline(o.name+"\t"+o.sex+"\t"+o.languages[1]);
console.read();
}
}
(2)使用索引器
class program
{
static void main(string[] args)
{
//json字符串
string jsonstr = @"{'languages':['c#','java'],'name':'*伟','sex':true}";
//反序列化
jobject o = jsonconvert.deserializeobject(jsonstr) as jobject;
//使用索引器访问
console.writeline(o["name"] + "\t" + o["sex"] + "\t" + o["languages"][1]);
console.read();
}
}