【发布时间】:2018-04-29 16:32:47
【问题描述】:
如何序列化 json 对象并将其传递给 api 调用,就像在此处发布的示例中的答案 Call web APIs in C# using .NET framework 3.5
System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
string s = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"EmailId\": \"admin@admin.com\",\"Password\": \"pass#123\"}")));
在 Postman 中我会这样做
var client = new RestClient("");
var request = new RestRequest(Method.POST);
request.JsonSerializer = new RestSharpJsonNetSerializer();
request.AddJsonBody(JsonObject);
但是,由于 .net framework 3.5 不支持 Postman,我必须使用 System.Net.WebClient。
【问题讨论】:
-
为什么要反序列化?您需要以序列化的形式发送它。
-
问题已编辑。我的意思是序列化,当然..
-
在这种情况下,看看 Newtonsoft 的 JSON.Net - 它几乎是 .NET 的事实上的 JSON 序列化程序(甚至微软都使用它)。
-
你可以使用
string s = client.UploadString("..","POST", JsonConvert.SerializeObject(yourObject)); -
真的就这么简单.. 嗯,我想到了,但认为也许有更好的方法。添加您的评论作为答案:)