Newtonsoft.Json解析Json字符串案例:

/// <summary>
        /// 上行jsom格式日志记录
        /// </summary>
        /// <param name="responseJson"></param>
        public static void WriteToMoJsomLog(string responseJson)
        {
            //{"error":"1","remark":"成功","statusbox":[{"mobile":"15510331875","taskid":"123","receivetime":"2015-01-01 00:00:00","errorcode":"dEv"},{"mobile":"13483728958","taskid":"124", "receivetime":"2015-02-01 00:00:00","errorcode":"back"}]}
            //{"error":"1","remark":"成功","callbox":[{"mobile":"15510331875","taskid":"","content":"a","receivetime":"0001-01-01 00:00:00", "extno":"123" },{"mobile":"13483728958","taskid":"","content":"b","receivetime":"0001-01-01 00:00:00","extno":"456"}]}
            try
            {
                MoObject obj = JsonDeserialize<MoObject>(responseJson);
                string pathConfig = App.GetSetting("TracePath");
                if (!string.IsNullOrWhiteSpace(pathConfig))
                {
                    Log4NetTraceListener log = new Log4NetTraceListener(pathConfig + @"\UserInterface");
                    if (obj.Error == 1)
                    {
                        foreach (MoContent item in obj.Callbox)
                        {
                            log.WriteLine("获取上行成功:error :1"+",Remark:"+obj.Remark);
                            log.WriteLine("获取上行返回信息:" + "mobile:" +item.Mobile+ ",taskid:" + item.TaskId + ",content:" + item.Content + ",receivetime:" + item.ReceiveTime + ",extno:" +item.Extno );

                        }
                    }
                    else
                    {
                        log.WriteLine("获取上行Json格式返回错误:error:"+obj.Error+"Remark:"+obj.Remark);
                    }
                }
            }
            catch (Exception ex)
            {

                throw new Exception("获取Json格式上行内容写入日志出错:" + ex);
            }

未解析建的类型:

/// <summary>
        /// 上行状态报告类型
        /// </summary>
        public class MoObject
        {
            public int Error { get; set; }
            public string Remark { get; set; }
            public MoContent[] Callbox { get; set; }
        }
        /// <summary>
        /// 上行和状态报告内容类型
        /// </summary>
        public class MoContent
        {
            public string Mobile { get; set; }
            public string TaskId { get; set; }
            public string Content { get; set; }
            public DateTime ReceiveTime { get; set; }
            public string Extno { get; set; }
            public string ErrorCode { get; set; }
        }

解析方法:

 public static T JsonDeserialize<T>(string json) where T : class
 {
      if (string.IsNullOrWhiteSpace(json))
      {
          throw new ArgumentException("json");
      }
      return JsonConvert.DeserializeObject<T>(json);
  }

 

posted on 2016-11-17 13:50  跨界农民工  阅读(422)  评论(0编辑  收藏  举报

导航