• NewtonSoft JSON For Net


    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<T>(@"{ 'Name':'zhangsan','Age':22}")

       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

  • 相关阅读:
    window7 上创建定时任务来运行自动化脚本
    初试接口测试
    list tuple dict (列表,元祖,字典间的相互转换)
    防止忘记的一些博客
    [python] 常用正则表达式爬取网页信息及分析HTML标签总结
    python正则表达式提取字符串
    关于json的dump和dumps
    三月23日测试Fiddler
    第六章 部署Python开发的web业务
    第五节 Nginx集群
  • 原文地址:https://www.cnblogs.com/sundh1981/p/13179525.html
Copyright © 2020-2023  润新知