//第一步 建立HTTP请求对象 var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; //第二步 生产请求报文 var requestObject = new { method="Query" ,senderId=senderId ,serviceId=serviceId ,userCardId=userCardId ,userCertId=userCertId ,userDept=userDept ,userName=userName , param= new { DataObjectCode = "NNNN" ,Condition="SFZH='11223344'" ,RequiredItems="[\"XM\",\"SFZH\"]" ,InfoCodeMode="1" } }; JavaScriptSerializer js = new JavaScriptSerializer(); string jsonData = js.Serialize(requestObject); //params是C#关键字,所以最后代替一下解决。 //'\'单引号在json序列化时会被译为unicode编码,最后解码即可。 textBox1.Text =jsonData= Regex.Unescape(jsonData.Replace("param", "params")); //DataContractJsonSerializer 序列化JSON需要显式定义类,且需要标记类成员属性,比较麻烦暂不用了 //DataContractJsonSerializer dj = new DataContractJsonSerializer(requestObject.GetType()); //MemoryStream msObj = new MemoryStream(); //dj.WriteObject(msObj, requestObject); //textBox1.AppendText("\n" + msObj.ToString()); try { //第三步 发送请求 using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(jsonData); streamWriter.Flush(); streamWriter.Close(); } //第四步 得到返回报文 var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var resualt = streamReader.ReadToEnd(); textBox2.Text = resualt; } } catch (Exception ex) { textBox2.Text = ex.Message; }
C# post json 匿名类 序列化
最新推荐文章于 2023-12-30 12:10:36 发布