I have trouble in retrieve data from Json Object from Restful.
Currently, I am using RestSharp to get the response from the api.
Based on what I have studied in Use C# to get JSON Data
I do not quite understand on the data retrieving. If I want to retrieve just a single data from the API,
Can I declared on specific data that I want to retrieve from the api in Model class or I need to declare every parameters from the API?
How do I retrieve only specific data from the API?
If the Api consists of an Object in outter part, how to do get the data in the nested object?
Please enlighten me on this matter. Thank you in advanced.
This is the sample code that I created,
var client = new RestClient(<myAPIkey>);
var request = new RestRequest(String.Format("post", Method.GET));
client.ExecuteAsync(request, response =>
{
Console.WriteLine(response.Content);
});
EDITED
I have edited my project as I am testing to get data from hardcoded Json data as such,
[{"id":"518523721","name":"ftyft"},
{"id":"527032438","name":"ftyftyf"},
{"id":"527572047","name":"ftgft"},
{"id":"531141884","name":"ftftft"}]
With Model class of,
public class TestInfo
{
public string id { get; set; }
public string name { get; set; }
}
and the code for deserialize,
TestInfo curTest = new TestInfo();
curTest = JsonConvert.DeserializeObject<TestInfo>(json1);
Console.WriteLine(curTest.id);
I still failed to get the id and name from the json data as it returns empty in Console.WriteLine. Can you please guide me through on how to read the json data?
Can I declared on specific data that I want to retrieve from the api
in Model class or I need to declare every parameters from the API?
It depends on the way which the api was designed. When you say parameters, are you trying to say routes or end-points? Your question is a little bit confused.
How do I retrieve only specific data from the API?
Can you be more specific? Are you talking about the route which you are trying to retrieve your data?
If the Api consists of an Object in other part, how to do get the
data in the nested object?
You can use Newtonsoft.Json(which is the most popular package in nuget) to deserialize your json object. Also, it will only be possible if you create an C# class which will be a mirror from your json model.
You can use an online tool like https://jsonutils.com/ to create this class automatically.
edit:
Since you are trying to deserialize a list of several objetcs, you should try the following approach:
var json1 =
"[{\"id\":\"518523721\",\"name\":\"ftyft\"},\r\n{\"id\":\"527032438\",\"name\":\"ftyftyf\"},\r\n{\"id\":\"527572047\",\"name\":\"ftgft\"}, \r\n{\"id\":\"531141884\",\"name\":\"ftftft\"}]";
var curTest = JsonConvert.DeserializeObject<List<TestInfo>>(json1);
Console.WriteLine(curTest[0].id);
It will works now.
Use the returned structure and put it on something like http://json2csharp.com/ to get a mapping object. And then you can deserialize it ref:
RootObject obj = new JavaScriptSerializer().Deserialize<RootObject>(response.Content);
//obj.YourDesiredProperty;
I was little late but it works for me.
var request = HttpWebRequest.Create(#"http://peerff.azurewebsites.net/api/team");
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
}
Related
I currently have an endpoint in my project:
[HttpPost("process")]
public IActionResult Process (string Val1, [FromBody] object Json)
{
//processing.....
Return Ok(...);
}
And on my client side I am trying to call this endpoint with WebClient like so:
string response = null;
string body = "{}";
using (var client = new WebClient())
{
client.UserDefaultCredentials = true;
client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
response = client.UploadString("localhost:55555/api/process?Val1=Param", body);
}
Here's where my concerns are:
For this endpoint, I will typically be passing a JSON object
However, I want this endpoint to also NOT require a body, I would want it to be empty, as the endpoint should not require it
If you look at my body variable - I am setting it to "{}" otherwise I've not found a different way to pass "EMPTY" body to the endpoint
Questions:
How do I properly pass an EMPTY body to this endpoint? (this endpoint will be used by different clients, and I am just looking for best practice approach to this?
In my endpoint, I have [FromBody] object Json parameter. Is it a better practice to have it be as object or can I alternatively do JObject that could still accept an Empty body
Forgive my "noobness" with these questions if they seem obvious, I'm just getting started in the API development and want to make sure I am using best practices.
You're currently using a WebClient, which is outdated in favour of HttpClient (see this answer). When using HttpClient you can post empty bodies as follows: await client.PostAsync("localhost:55555/api/process?Val1=Param", null);
As for your second question. Look into Data Transfer Objects, aka DTOs. They are in a nutshell dumb types you can use purely for passing and receiving data through your API, you can add things like validation to them as well. Using object or JObject is only needed if you're receiving dynamic data, otherwise use DTOs where possible.
I have created a basic ASP.Net Web Application and I am trying to use the OpenWeatherMap API with this. (first time dealing with APIs).
The Info I have about the WebAPI is:
You can search weather forecast for 5 days with data every 3 hours by city name. All weather data can be obtained in JSON and XML formats.
There is a possibility to receive a central district of the city/town with its own parameters (geographic coordinates/id/name) in API response. Example
API call:
api.openweathermap.org/data/2.5/forecast?q={city name},{country code}
Parameters:
q city name and country code divided by comma, use ISO 3166 country codes
Examples of API calls:
api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml
Currently I have this working when I use the api that returns a json object
api.openweathermap.org/data/2.5/weather?q=London&units=metric
However if I simply change the URL to the first (which returns the XML) my application no longer retrieves the data from the API.
I have tried amended the mode=xml into mode=json but still no avail.
How can I use the first web API?
Many thanks
--Edit:
In my model class i have the following method:
string url = "api.openweathermap.org/data/2.5/…;
var client = new WebClient();
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return jsonContent;
(taken out the key) I then call this method from my view. However I cannot use that api call that has the =xml at the end
your problem is when result is returned as xml, you are using a JavaScriptSerializer to Deserialize it.
xml is not json, hence the Deserialization would have failed
what you need is a XmlSerializer to deserializae the result
below is some code to get you started:
string url = #"http://samples.openweathermap.org/data/2.5/forecast?q=London&appid=b1b15e88fa797225412429c1c50c122a1&mode=xml";
var client = new WebClient();
var content = client.DownloadString(url);
XmlSerializer serializer = new XmlSerializer(typeof(weatherdata));
weatherdata result = null;
using (TextReader reader = new StringReader(content))
{
result = (weatherdata)serializer.Deserialize(reader);
}
notice that typeof weatherdata - it is no point of Deserialize into non strong type object if you are going to deserialize into object,
there is noting you can do with it.
if you don't want to hand code the strong type model, copy the xml result into clipboard then use VS (not sure other version but 2017 as example) toolbar
Edit -> paste special -> Paste xml as classes to generate the strong type class for you
I would like to make a console application that can query a website for data, process it, and then display it. ie- Access http://data.mtgox.com/ and then display the rate for currency X to currency Y.
I am able to get a large string of text via WebClient and StreamReader (though I don't really understand them), and I imagine that I could trim down the string to what I want and then loop the query with a delay to enable updating of the data without running the program again. However I'm only speculating and it seems like there would be a more efficient way of accessing data than this. Am I missing something?
EDIT - The general consensus seems to be to use JSON to do this; which is exactly was I was looking for! Thanks guys!
It looks like that site provides an API serving up JSON data. If you don't know what JSON is you need to look into that, but basically you could create object models representing this JSON. If you have the latest version of VS2012 you can copy the JSON and right click, hit paste special, then paste as class. This will automatically generate models for you. You then contact the API, retrieve the JSON, deserialize it into your models, and do whatever you want from there.
A better way:
string url = "http://data.mtgox.com/";
HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET"; // This can also be "POST"
HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
string myPageSource = string.Empty;
myPageSource= myWebSource.ReadToEnd();
myWebResponse.Close();
// Do something with the data in myPageSource
Once you have the data, look at JSON.NET to parse it
I want to take existing data and put it into RavenDB.
My existing data was in an XML format, so I converted it to JSON.
What should my next step be?
Can I store it in RavenDB as is?
Do I need to create new objects to store it?
Thanks in advance!
It is not mandatory to submit content to RavenDB using the RavenDB Client, nor is it necessary to populate a domain model first. This is unnecessary effort and only complicates the process of data submission/insertion/migration/import.
You can submit JSON formatted documents directly to RavenDB using the HTTP API, specifically you may wish to review the "Single Document Operations" topic for simple examples which (currently) show examples using 'curl'.
Consider the following .NET code:
var url = string.Format("http://ravendb-server:8080/databases/{0}/docs/{1}", databaseName, docId);
var webRequest = System.Net.HttpWebRequest.CreateHttp(url);
webRequest.Method = "PUT";
webRequest.ContentType = "application/json";
webRequest.Headers["Raven-Entity-Name"] = entityName;
var stream = webRequest.GetRequestStream();
using (var writer = new System.IO.StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(json);
}
var webResponse = webRequest.GetResponse();
webResponse.Close();
The above snippet allows you to submit a valid JSON document into a specific database and a specific document collection with the specified ID. Database selection and ID designation is performed through URL paths, and the Document Collection is specified with the metadata header Raven-Entity-Name.
There are additional metadata headers you may want to send up, such as Raven-Clr-Type or Last-Modified but they are not required.
I suppose that your json-data represents the data of your applications domain, and you want to have classes with properties to work with that data in your application, right?
If that is the case, you need to write a simple import-application, that populates your domain model once and then stores all your objects as regular RavenDB documents, just the way you would store any other object with RavenDB.
Does that make sense?
I am looking at adding SMS abilities to my WCF service. I found a cheap SMS service called Penny SMS.
Their interface supports json. But I have no idea how to call it in my WCF service.
Here is the interface/example:
Sample JSON-RPC Request
{ "method": "send",
"params": [
"YOUR_API_KEY",
"msg#mycompany.com",
"5551231234",
"Test Message from PENNY SMS"
]
}
How would I call that with C# from a WCF service? What I am looking for is a way to wrap this into a method call. Something like:
StaticSMSClass.SendSMS("1234567890", "My Message to send");
Note they also support an XML-RPC API if that is more doable from C#.
UPDATE: I made a stab at creating a call myself, but it did not work. I am going to post my attempt in a separate question and see if anyone has a way to do it.
You need to send a HTTP POST with the JSON message to the remote server. You can do this with HttpWebRequest. You either build the JSON manually (the messages seem simple), or define types for it and use a JSON serializer.
MSDN has an example, for your case it would look something like (untested):
string json = // Your JSON message
WebRequest request = WebRequest.Create ("http://api.pennysms.com/jsonrpc");
request.Method = "POST";
var postData = Encoding.UTF8.GetBytes(json);
request.ContentLength = postData.Length;
request.ContentType = "text/json";
using(var reqStream = request.GetRequestStream())
{
reqStream.Write(postData);
}
using(var response = request.GetResponse())
{
// Response status is in response.StatusCode
// Or you can read the response content using response.GetResponseStream();
}
See my answer to the question "Client configuration to consume WCF JSON web service" for how the create a JSON client with WCF.
The answers so far are good, but one additional thing you can take advantage of (since you are within a WCF service) is the use of DataContractJsonSerializer.
In particular, I refer to how you actually populate your JSON in the first line of driis's example.
string json = // Your JSON message
Now, one of the best ways to do this may be to create a new class with these members:
[DataContract]
class SomeType
{
[DataMember]
string method;
[DataMember]
string[] params;
}
Then, just create an instance of SomeType every time and serialize it to JSON using the DataContractJsonSerializer every time you want to send over a piece of data. See http://msdn.microsoft.com/en-us/library/bb412179.aspx for how to use the DataContractJsonSerializer stand-alone.
Hope this helps!
Check the WCF REST API. They serve JSON, maybe they also can send JSON (in intra WCF solution it works). Maybe you have to construct the contract in wsdl to get the service running but maybe it works out.