WPF(6)---json數據的接收與發送


模擬發送:{"op":"UpdateDeviceStatus","monitor":{"File":"true","Smoke":"true"}}

獲取命令:{"op":"GetMessage","issuccess":null,"context":{}}

服務端返回命令:"{"op":null,"issuccess":"true","context":{"File":"true","Smoke":"true"}}

對json的解析:

                //將字符串轉為json形式
                JObject MyJObject = JObject.Parse(PostData);
                //解碼json
                Myop = MyJObject["op"].ToString();

1----webservce服務端

  (1)序列化JSON數據({"op":null,"issuccess":null,"context":{}})

 //序列化json數據
        private class SendJson
        {
            public string op { get; set; }
            public string issuccess { get; set; }
            private Dictionary<string,object> _context = null;
            public Dictionary<string, object> context
            {
                get
                {
                    if (this._context == null)
                    {
                        this._context = new Dictionary<string, object>();
                    }
                    return this._context;
                }
                set
                {
                    this._context = value;
                }
            }
        }
        public class _Data  //暫時保存數據
        {
            public static string _MyFile = "null";
            public static string _MySmoke = "null"; 
        } 

  (2)對請求方式的判斷

 if (context.Request.RequestType != "POST" || context.Request.ContentType.ToLower().IndexOf("application/json") == -1)
            {
               SendJson MySendJson = new SendJson();
               string strMySendJson = JsonConvert.SerializeObject(MySendJson);
               context.Response.ContentType = "application/json";
               context.Response.Write(strMySendJson);
               return;
           }

(3)接收傳入數據

 //當請求方式為POST時 獲取傳入內容
            var StreamDate = context.Request.InputStream;
            string MyFile;
            string MySmoke;
            string Myop;
            using (StreamReader MyStreamReader = new StreamReader(StreamDate))
            {   
                //讀傳入的數據
                string PostData = MyStreamReader.ReadToEnd();
                //對傳入的URL數組進行解碼 轉換為字符串
                PostData = System.Web.HttpUtility.UrlDecode(PostData);
                //將字符串轉為json形式
                JObject MyJObject = JObject.Parse(PostData);
                //解碼json
                Myop = MyJObject["op"].ToString();
                //對op方法進行判斷
                if (Myop == "UpdateDeviceStatus")
                {
                    MyFile = MyJObject["monitor"]["File"].ToString();
                    MySmoke = MyJObject["monitor"]["Smoke"].ToString();
                    _Data._MyFile = MyFile;
                    _Data._MySmoke = MySmoke;
                    context.Response.ContentType = "application/json";
                    context.Response.Write(SendMessage(Myop, MyFile, MySmoke));
                }
                if (Myop == "GetMessage")
                {
                    MyFile = _Data._MyFile;
                    MySmoke = _Data._MySmoke;
                    context.Response.ContentType = "application/json";
                    context.Response.Write(SendMessage(Myop, MyFile, MySmoke));
                }
            }
        }

(4)數據處理過程

        private string SendMessage(string Myop,string MyFile,string MySmoke)
        {
            SendJson MySendJson = new SendJson();
            switch(Myop)
            {
                case "UpdateDeviceStatus":
                    if(MyFile!=""&MySmoke!="")
                    {
                        MySendJson.issuccess="true";
                        MySendJson.op = "updateDeviceStatus";
                    }
                    else
                    {
                        MySendJson.op = "updateDeviceStatus";
                        MySendJson.issuccess="false";
                    } break;
                case "GetMessage":
                     if(MyFile=="false")
                     {
                         MySendJson.issuccess="true";
                         MySendJson.context.Add("File", "false");
                     }
                    else if(MyFile=="true")
                     {
                         MySendJson.issuccess="true";
                         MySendJson.context.Add("File", "true");
                     }
                     if(MySmoke=="false")
                     {
                         MySendJson.issuccess="true";
                         MySendJson.context.Add("Smoke", "false");
                     }
                     else if (MySmoke == "true")
                     {
                         MySendJson.issuccess="true";
                         MySendJson.context.Add("Smoke", "true");
                     }
                     if (MySmoke == "null" & MyFile == "null")
                     {
                         MySendJson.issuccess = "false";
                         MySendJson.context.Add("Smoke", "false");
                         MySendJson.context.Add("File", "false");
                     }
                    break;
                default:
                    MySendJson.op = "方法錯誤";
                break;
            }
            return JsonConvert.SerializeObject(MySendJson);
        }

2---客戶端接收與發送json數據

   1===》發送

   (1)序列化json數據格式

 private class MoNiSendJson
        {
            public string op { get; set; }
            private Dictionary<string, object> _context = null;
            public Dictionary<string, object> monitor
            {
                get
                {
                    if (this._context == null)
                    {
                        this._context = new Dictionary<string, object>();
                    }
                    return this._context;
                }
                set
                {
                    this._context = value;
                }
            }
        }

  (2)發送json數據

 private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            //創建發送json字符串
            MoNiSendJson MyMoNiSendJson=new MoNiSendJson();
            MyMoNiSendJson.op = "UpdateDeviceStatus";
            MyMoNiSendJson.monitor.Add("File","true");
            MyMoNiSendJson.monitor.Add("Smoke","true");
            string strMySendJson = JsonConvert.SerializeObject(MyMoNiSendJson);
            //post方式發送
            HttpWebRequest MyHttpWebRequest = null;
            HttpWebResponse MyHttpWebResponse = null;
            MyHttpWebRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["MyUrl"]);
            MyHttpWebRequest.ContentType = "application/json";
            byte[] Mybyte = Encoding.UTF8.GetBytes(strMySendJson);
            MyHttpWebRequest.ContentLength = (long)Mybyte.Length;
            MyHttpWebRequest.Method = "POST";
            Stream MyStream = MyHttpWebRequest.GetRequestStream();
            MyStream.Write(Mybyte, 0, Mybyte.Length);
            MyStream.Close();
            //接收過程
            MyHttpWebResponse = (HttpWebResponse)MyHttpWebRequest.GetResponse();
            StreamReader MyStreamReader = new StreamReader(MyHttpWebResponse.GetResponseStream(), Encoding.UTF8);
            string MyJsonRead = MyStreamReader.ReadToEnd(); MyStreamReader.Close(); MyHttpWebResponse.Close();
        }

 2===》接收json

    (1)序列化json

//序列化json數據
        private class SendJson
        {
            public string op { get; set; }
            public string issuccess { get; set; }
            private Dictionary<string, object> _context = null;
            public Dictionary<string, object> context
            {
                get
                {
                    if (this._context == null)
                    {
                        this._context = new Dictionary<string, object>();
                    }
                    return this._context;
                }
                set
                {
                    this._context = value;
                }
            }
        }

  (2)接收json數據

 private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            //創建發送json字符串
            SendJson MySendJson = new SendJson();
            MySendJson.op = "GetMessage";
            string strMySendJson = JsonConvert.SerializeObject(MySendJson);
            //post方式發送
            HttpWebRequest MyHttpWebRequest = null;
            HttpWebResponse MyHttpWebResponse = null;
            MyHttpWebRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["MyUrl"]);
            //請求的數據格式
            MyHttpWebRequest.ContentType = "application/json";
            //設置請求方式
            MyHttpWebRequest.Method = "POST";
            //轉換為byte[] 數組
            byte[] Mybyte = Encoding.UTF8.GetBytes(strMySendJson);
            //設置標頭
            MyHttpWebRequest.ContentLength = (long)Mybyte.Length;
            //創建stream 用來發送
            Stream MyStream = MyHttpWebRequest.GetRequestStream();
            MyStream.Write(Mybyte, 0, Mybyte.Length);
            MyStream.Close();
            //接收數據
            MyHttpWebResponse = (HttpWebResponse)MyHttpWebRequest.GetResponse();
            StreamReader MyStreamReader = new StreamReader(MyHttpWebResponse.GetResponseStream(), Encoding.UTF8);
            string MyJsonRead = MyStreamReader.ReadToEnd();
            MyStreamReader.Close();
            MyHttpWebResponse.Close();
            //將接收道德數據轉換為jsoon 字符形式 
            JObject jo = JObject.Parse(MyJsonRead);
            //對發來數據解析
            string Fire=jo["context"]["File"].ToString();
            string Smoke = jo["context"]["Smoke"].ToString();
            if (Fire == "true")
            {
                this.lblFire.Content = "着火了";
            }
            else
            {
                this.lblFire.Content = "沒有着火!";
            }
            if (Smoke == "true")
            {
                this.lblSmoke.Content = "有煙";
            }
            else
            {
                this.lblSmoke.Content = "無煙!";
            }
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM