1. 序列化 对象
/** 使用 Newtonsoft.Json 序列化对象 **/ [WebMethod]
public String getPersonInfos() {
// 初始化数据
List < Pserson > mlist = new List < Pserson > ();
for (int i = 0; i < 5; i++)
{
Pserson mpersopn = new Pserson();
mpersopn.name = "张三";
mpersopn.sex = i % 2 == 0 ? "男" : "女";
mpersopn.age = 20 + i;
mlist.Add(mpersopn);
}
CallbackObject mcallback = new CallbackObject();
mcallback.falg = "200";
mcallback.message = "请求成功";
mcallback.result = mlist;
String str = JsonConvert.SerializeObject(mcallback);
return str;
}
2. 反序列化 json字符串
/** 使用 Newtonsoft.Json 反序列化json字符串 **
[WebMethod]
public List < Pserson > getPersonInfo()
{
string jsonText = "[{'name':'张三','sex':'男','age':30},{'name':'李四','sex':'女','age':25}]";
List < Pserson > personlist = JsonConvert.DeserializeObject < List < Pserson >> (jsonText);
foreach(Pserson p in personlist) {
System.Diagnostics.Debug.WriteLine("\n\n");
String str = "name = " + p.name + "\t sex = " + p.sex + "\t age = " + p.age + "\n";
System.Diagnostics.Debug.WriteLine(str);
}
return personlist;
}
var result = JsonConvert.DeserializeAnonymousType(client.Execute(request).Content, new { access_token = string.Empty, expires_in = string.Empty });
var o2 = JsonConvert.DeserializeObject(json) as JObject;