使用Newtonsoft.Json处理含有未知节点的JSON

来源:互联网 发布:js 从数据库导出excel 编辑:程序博客网 时间:2024/06/06 06:59
  string s = string.Empty;

  string JSONStr = this.txtJSONStr.Text;

JSON字符串转对象的两种方法,含未知JSON元素

格式:        {"ProcessName":21,"Folio":11,"CurrentUser":31,"Parameters":{"FormID":"3","CheckMessage":"1111"}}

Parameters不固定。

一、 将Parameters转为JObject再 使用dynamic 循环获取

{

                JObject objJ = JObject.Parse(JSONStr);//创建JObject对象
                string ProcessName = objJ["ProcessName"].ToString();
                string Folio = objJ["Folio"].ToString();
                string CurrentUser = objJ["CurrentUser"].ToString();
                string JSONParameters = objJ["Parameters"].ToString();
                JObject objParameters = JObject.Parse(JSONParameters);
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dynamic parsedObject = objParameters;
                foreach (var item in objParameters)
                {
                    dict.Add(item.Key.ToString(), item.Value.ToString());
                }
            }

二、 使用Model(推荐)

 public class JSONBean
    {
        public JSONBean()
        { }
        public Dictionary<string, string> Parameters;
        /// <summary>
        /// 
        /// </summary>
        public int ProcessName { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int Folio { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int CurrentUser { get; set; }
        /// <summary>
        /// 
        /// </summary>
    }

{

                JSONBean jb = JsonConvert.DeserializeObject<JSONBean>(JSONStr);
                s += jb.CurrentUser;
                s += jb.Folio;
                s += jb.ProcessName;
                foreach (var item in jb.Parameters)
                {
                    s += "\r\n" + item.Key + ":" + item.Value + "\r\n";
                }
            }
            this.txtMSG.Text = s;
原创粉丝点击