0

How can you serialize a json object and pass it on to an api call, like the one in the example posted as an answer here 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\": \"[email protected]\",\"Password\": \"pass#123\"}")));

In Postman I would just do this

 var client = new RestClient("");
 var request = new RestRequest(Method.POST);
 request.JsonSerializer = new RestSharpJsonNetSerializer();
 request.AddJsonBody(JsonObject);

However, as Postman is not supported in .net framework 3.5, I have to use System.Net.WebClient.

7
  • Why do you want to deserialize it? You need it in a serialized form to send it. Commented Nov 16, 2017 at 8:12
  • Question edited. I meant serialized, of course.. Commented Nov 16, 2017 at 8:13
  • 1
    In that case, look at Newtonsoft's JSON.Net - it's pretty much the de facto JSON serializer for .NET (to the point that even Microsoft use it). Commented Nov 16, 2017 at 8:15
  • 1
    You can use string s = client.UploadString("..","POST", JsonConvert.SerializeObject(yourObject)); Commented Nov 16, 2017 at 8:22
  • 1
    Really that simple.. Huh, I thought of that, but thought there perhaps was a better approach. Add your comment as an answer :) Commented Nov 16, 2017 at 8:25

1 Answer 1

1

You can do what you want with WebClient (and Json.NET package) like this:

var yourObject = new YourObject {
    Email = "email",
    Password = "password"
};
string s = client.UploadString("http://localhost:1111/Service.svc/SignIn","POST", JsonConvert.SerializeObject(yourObject));
Sign up to request clarification or add additional context in comments.

3 Comments

@miniHessel ah sorry I missed about .NET 3.5. Maybe there are indeed not much options there, not sure.
I think there isn't. Do you know how to check for status code like this IRestResponse response = client.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) return true; with WebClient?
Seems there is no direct way, but you can check this: stackoverflow.com/q/3574659/5311735. Though if response code is not successful (not in 2xx range) - it should throw an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.