POST Web Service Client using C# - c#

Can you please give me a sample example of how to make the JSON request body in C#. I am using Visual Studio 2015. I know SOAP UI, but I am new to C#.
Thanks in advance.

You can try the following
Lets assume you have the following webmethod
public void Webmethod(string parameter)
{
//Do what ever
}
In C# you will do the following to call the webmethod, You require Json.net, Newtonsoft or other Json serializer
var webRequest = WebRequest.Create("http:\\www.somesite.com/path/to/webservice/webservice.asmx/Webmethod");
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
Build a Json object representing the parameters
var jsonobjectrepresentingparameters = new {parameter = "Value"};
Get the Json string using Newtonsoft JsonConvert
var datastring = Newtonsoft.Json.JsonConvert.SerializeObject(jsonobjectrepresentingparameters);
Get the bytes
var bytes = Encoding.ASCII.GetBytes(datastring);
Write the bytes to the request
var requestStream = webRequest.GetRequestStream();
requestStream.Write(bytes, 0,bytes.Length);
Get repsonse
var response = webRequest.GetResponse();
If your Webmethod returned anything like a string, int or other data you can use the following class to deserialize
public class Type<T>
{
public T D { get; set; }
public Type()
{
}
}
You will notice when you work with webservices it returns a json object with property d as the value which is why you require the above class in C#
Then you will require the following extra two lines if your return type was string
var json = (new StreamReader(response.GetResponseStream())).ReadToEnd();
var object = JsonConvert.DeserializeObject<Type<string>>(json);

Related

Limiting a JSON string response from an API to select attributes

Currently, I am using a [WebMethod] to call an API and get the response as a JSON string.
public string GetFloodData()
{ ...
WebRequest requestObj = WebRequest.Create(url);
requestObj.Method = "GET";
requestObj.ContentType = "application/json";
responseObj = (HttpWebResponse)requestObj.GetResponse();
using (Stream stream = responseObj.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresult = sr.ReadToEnd();
sr.Close();
}
return strresult;
...
}
When I call GetFloodData(), I get the following response in the browser:
<string xmlns="http://tempuri.org/">
{"ListEvents":
[{"EventID":1,"EventName":"Debby2000","State":"PR","EventType":"Tropical or
Extratropical","Days":5,"LSTStart":"\/Date(9666432000000000)\/",
"LSTEnd":"\/Dat e(967075200000-0000)\/"}, {...}....]}
At this point (before I parse it as a formal JSON Object), I just want to eliminate the stuff I don't want ("Days","LSTStart", and "LSTEnd") and keep what I want. How would I limit what attributes are returned in my response?
You can de-serialise it with a class, and in that class, you can write only the variables you do want to keep. Although, keep the structure of the Json and the class as same. Variables can be missing, but the structure should be the same

a c# class that contain all json properties of google maps api

ok, so I am trying to use JSON.net to purse the JSON string of google maps API to an object:
string url = #"https://maps.googleapis.com/maps/api/directions/json?origin=75+9th+Ave+New+York,+NY&destination=MetLife+Stadium+1+MetLife+Stadium+Dr+East+Rutherford,+NJ+07073&key=YOUR_API_KEY";
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
StreamReader reader = new StreamReader(data);
string responseFromServer = reader.ReadToEnd();
response.Close();
var result = JsonConvert.DeserializeObject<T>(responseFromServer);
^
|
here
and I need to replace the T with the object that contains all the JSON fields example:
class ex
{
int[] arr;
string str;
(....)
}
however, the JSON string that returned from google maps API is very long and contains many fields, and as I'm pretty new to JSON, I will probably get this wrong. I wonder if there is a way to auto-generate a class to contain all these properties (maybe anonymous types, somehow?) or if someone did this class before me and open-sourced it?
thank you in advance!

How to call POST RESTFUL service thru Console application

I have a rest ful service (POST) which accepts Json object as an input (Request body in Fiddler). Now I wanted to consume the service from Console Applciation with dynamic values (either read from text file or hardcoded values). I will log the actions like, for this test data XXXXX, the service returns values.
Can any one help me how to automate this process. I wold like to comsume this service from Console application.
Pls note Output also JSON string.
Any suggestion will be really helpful for me.
To make the POST request, something like:
var req = WebRequest.Create(url);
var enc = new UTF8Encoding(false);
var data = enc.GetBytes(serializedJson);
req.Method = "POST";
req.ContentType = "application/json";
req.ContentLength = data.Length;
using (var sr = req.GetRequestStream())
{
sr.Write(data, 0, data.Length);
}
var res = req.GetResponse();
var res= new StreamReader(res.GetResponseStream()).ReadToEnd();
You can easily create the serializedJson from an object like:
var serializedJson = Newtonsoft.Json.JsonConvert.SerializeObject(myDataObject);
Install the following web api package from nuget in your console project
Add a reference to System.Net.Http and System.Runtime.Serialization
Create a contract class of the data you want to send and receive (the same as in your webservice)
[DataContract]
public class YourObject{
[DataMember]
public int Id {get; set;}
}
In your console app call the webservice like this:
var client = new HttpClient();
var response = client.PostAsJsonAsync<YourObject>("http://yourserviceurl:port/controller", objectToPost).Result;
if(response.IsSuccessStatusCode){
Console.WriteLine(response);
}else{
Console.WriteLine(response.StatusCode);
}
More info about webapi here and here

Deserializing JSON List object

I receive this JSON object from a web request:
"\"[{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-12T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-17T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-13T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-18T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-14T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-19T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-15T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-20T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-16T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-21T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"}]\""
I have an object that matches this type called EventView and deserialize it into an object like so:
string result = "";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
JavaScriptSerializer jss = new JavaScriptSerializer();
JsonEventView ev = jss.Deserialize<JsonEventView>(result);
public class JsonEventView
{
public List<EventView> results { get; set; }
}
However, I get an error every time I attempt to deserialize it.
Cannot convert object of type 'System.String' to type 'EventManagerService.JsonEventView'
Web API handles the serialization for you. So you do not need to manually serialize the object to JSON.
return Request.CreateResponse(HttpStatusCode.OK, Active);
Of course, Web API being able to return JSON hinges on Content Negotiation and your app being properly configured, such that there is a formatter that can provide the output a consumer requests (JSON in this case).

using dynamic keyword when parse JSON

I'm newbie to using the dynamic keyword in C#. It seems simple enough, but I can't seem to use it effectively.
I see this example from Facebook:
var client = new FacebookClient();
dynamic me = client.Get("totten");
string firstname = me.first_name;
it works fine, but if you look at me in a debugger, then you can see that client.Get() returns simple JSON. The same it's said in Facebook documentation:
The result of this request is a dynamic object containing various
properties such as first_name, last_name, user name, etc. You can see
the values of this request by browsing to
http://graph.facebook.com/totten in your web browser. The JSON result
is shown below.
I want to do the same dodge with returned JSON from Foursquare:
private static string GetReturnedUrlFromHttp(string url)
{
HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
webRequest.Timeout = 10000;
webRequest.Method = "GET";
WebResponse response = webRequest.GetResponse();
string responseStr = String.Empty;
using (var stream = response.GetResponseStream())
{
var r = new StreamReader(stream);
responseStr = r.ReadToEnd();
}
return responseStr;
}
public static void FillDataFromFoursquareUsingDynamic()
{
string foursquare_url_detail = "https://api.foursquare.com/v2/venues/4b80718df964a520e57230e3?locale=en&client_id=XXX&client_secret=YYY&v=10102013";
dynamic responseStr = GetReturnedUrlFromHttp(foursquare_url_detail);
var response = responseStr.response;
}
I got the following error:
'string' does not contain a definition for 'response'
Why am I getting this error and is it possible to 'parse' any JSON string like in Facebook?
FacebookClient.Get doesn't really return the JSON string. Instead it parses the string into a dynamic object with properties matching the names of the values in the JSON string.
Using dynamic doesn't magically turn a string into an object with the properties defined in the string. Instead, you need to first parse the string with the help of a JSON library like JSON.NET.

Categories

Resources