1.JSONConvert 序列化与反序列化
string js=JSONConvert.SerialObject(object obj) 对象序列化成JSON格式字符串
例子:string js=JSONConvert.SerailObject(new{Name="zhangsan",Age=22});
结果: {"Name":"zhangsan","Age":22};
反序列化:
T obj=JSONConvert.DeserializeObject
textBox1.Text=obj.Name;
// zhangsan
2.JSON.Linq
public static JObject JObject.Parse(string json)
JObject jo=JObject.Parse(string jsonString);
例子:
JObject jo = JObject.Parse(@"{'Name':'sundh','Age':25}");
textBox1.AppendText(jo["Name"].ToString());
结果:sundh
JArray ja=JArray.Parse(@"['aa','bb','cc']");
textBox1.Text=ja.ToString();
//结果:["aa","bb","cc"]
2.1 SelectToken(string item)
JObject jo = JObject.Parse(@"{'Student':{'Name':'zhangsan','Age':'15'},'Score':{'YuWen':89,'ShuXue':67,'YingYu':95}}");
JObject jStudent = jo.SelectToken("Student") as JObject; //方法1 返回值为JToken
JObject js = jo["Student"] as JObject; //方法2 返回值为:JToken 因此需要转换
textBox1.Text = jStudent.ToString();
textBox1.Text += js;
//结果:
{
"Name": "zhangsan",
"Age": "15"
}{
"Name": "zhangsan",
"Age": "15"
}
public void Add(string propertyName,JToken value)
JObject jo = JObject.Parse(@"{'Student':{'Name':'zhangsan','Age':'15'},'Score':{'YuWen':89,'ShuXue':67,'YingYu':95}}");
JObject jStudent = jo.SelectToken("Student") as JObject;
JObject js = jo["Student"] as JObject;
js.Add("ls", jo);
//结果
{
"Name": "zhangsan",
"Age": "15",
"ls": {
"Student": {
"Name": "zhangsan",
"Age": "15"
},
"Score": {
"YuWen": 89,
"ShuXue": 67,
"YingYu": 95
}
}
}
public abstract class JToken : IJEnumerable<JToken>, IEnumerable<JToken>, IEnumerable, IJsonLineInfo, ICloneable, IDynamicMetaObjectProvider
public class JObject : JContainer, IDictionary<string, JToken>, ICollection<KeyValuePair<string, JToken>>, IEnumerable<KeyValuePair<string, JToken>>, IEnumerable, INotifyPropertyChanged, ICustomTypeDescriptor, INotifyPropertyChanging
public class JArray : JContainer, IList<JToken>, ICollection<JToken>, IEnumerable<JToken>, IEnumerable
public class JValue : JToken, IEquatable<JValue>, IFormattable, IComparable, IComparable<JValue>, IConvertible
根据定义可知JToken,对共享元素的一种抽象,即它抽象了JObject元素。
API Document:https://www.newtonsoft.com/json/help/html/N_Newtonsoft_Json_Linq.htm