在C#中,我們可以使用JsonConvert類將一個(gè)對(duì)象序列化為Json字符串,并將其傳輸?shù)椒?wù)器上。
//創(chuàng)建一個(gè)對(duì)象 Person person = new Person(); person.Name = "張三"; person.Age = 18; person.Sex = "男"; //將對(duì)象序列化為Json字符串 string jsonString = JsonConvert.SerializeObject(person); //創(chuàng)建一個(gè)HttpWebRequest對(duì)象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.server.com/api"); //設(shè)置請(qǐng)求方法為Post request.Method = "POST"; //設(shè)置請(qǐng)求數(shù)據(jù)格式為Json request.ContentType = "application/json"; //將Json字符串轉(zhuǎn)換成字節(jié)數(shù)組 byte[] bytes = Encoding.UTF8.GetBytes(jsonString); //設(shè)置請(qǐng)求內(nèi)容長(zhǎng)度 request.ContentLength = bytes.Length; //將數(shù)據(jù)寫入請(qǐng)求流中 Stream requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); //發(fā)送請(qǐng)求 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //對(duì)服務(wù)器返回的結(jié)果進(jìn)行處理 Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); string result = reader.ReadToEnd(); Console.WriteLine(result);
在上面的示例中,我們首先創(chuàng)建了一個(gè)對(duì)象,并使用JsonConvert類的SerializeObject方法將其序列化為Json字符串。然后,我們創(chuàng)建了一個(gè)HttpWebRequest對(duì)象,并設(shè)置了請(qǐng)求的方法和內(nèi)容類型。接下來(lái),我們將Json字符串轉(zhuǎn)換為字節(jié)數(shù)組,并將其寫入請(qǐng)求流中。最后,我們發(fā)送請(qǐng)求并對(duì)服務(wù)器返回的結(jié)果進(jìn)行處理。