I want to use Goolge AJAX Feed API in my C# console application to save return feeds as C# collection so i can use this .net collcetion in my .net application.
I noticed google give a Java Access Code Snippets but I have no idea how to coding it in C#.
I know there is a very good .net opensource library Json.NET we can use to read and write JSON formatted data.
Can someone give me an exmpale how to use C# and Json.NET play with Google AJAX Feed API?
Final Solution:
public class FeedApiResult
{
public ResponseData responseData { get; set; }
public string responseDetails { get; set; }
public string responseStatus { get; set; }
}
public class ResponseData
{
public Feed feed { get; set; }
}
public class Feed
{
public string title { get; set; }
public string link { get; set; }
public string author { get; set; }
public string description { get; set; }
public string type { get; set; }
public List<Entry> entries { get; set; }
}
public class Entry
{
public string title { get; set; }
public string link { get; set; }
public string author { get; set; }
public string publishedDate { get; set; }
public string contentSnippet { get; set; }
public string content { get; set; }
}
var url = "http://ajax.googleapis.com/ajax/services/feed/load?q=http%3A%2F%2Fwww.digg.com%2Frss%2Findex.xml&v=1.0";
var wc = new WebClient();
var rawFeedData = wc.DownloadString(url);
//You can use System.Web.Script.Serialization if you don't want to use Json.NET
JavaScriptSerializer ser = new JavaScriptSerializer();
FeedApiResult foo = ser.Deserialize<FeedApiResult>(rawFeedData);
//Json.NET also return you the same strong typed object
var apiResult = JsonConvert.DeserializeObject<FeedApiResult>(rawFeedData);
I've just looked at the examples, and here is how I'd go about it.
Construct the feed Url (read the documentation)
Use the WebClient to Download the URL as a String.
Use Json.NET to reads the string.
Use a for-loop to read each entries
For example, a quick untested hack:
// 1.
var url = "'http://ajax.googleapis.com/ajax/services/feed/load?q=http%3A%2F%2Fwww.digg.com%2Frss%2Findex.xml&v=1.0";
// 2.
var wc = new WebClient();
var rawFeedData = wc.DownloadString(url);
// 3.
var feedContent = JObject.Parse(rawFeedData);
// ...
var entries = feedContent["entries"];
for (int i = 0; i < entries.Length; i++) {
var entry = entries[i];
// insert entry into your desired collection
}
If however, you want strongly-typed class, you must first make a class that "looks like" the data that is returned from the feed api first, i.e.
public class FeedApiResult {
public FeedApiFeedObj responseData { get; set; }
// snip ...
}
public class FeedApiFeedObj {
public string title { get; set; }
public string link { get; set; }
// snip ...
}
Then in step #3, you can use the deserializing method like this:
var apiResult = JsonConvert.DeserializeObject<FeedApiResult>(feedContent)
...
Hope this helps!
Related
I am trying to access a simple REST Api, https://api.cryptonator.com/api/ticker/btc-usd
The result of the same is like this format:
{"ticker":{"base":"BTC","target":"USD","price":"9969.76308171","volume":"127575.47420967","change":"-197.36472278"},"timestamp":1517410741,"success":true,"error":""}
Now, when I am trying to get result from it, I find ticker objet of json null, timestamp and error objects are getting filled.
So, I suspect there might be the problem datamembers are not matching with json text. My Modeldto looks like this:
public class CurtoUsd
{
public ticker tick { get; set; }
public Single timestamp { get; set; }
public bool success { get; set; }
public string error { get; set; }
}
public class ticker
{
public string _base { get; set; }
public string target { get; set; }
public string price { get; set; }
public string volume { get; set; }
public string change { get; set; }
}
Please have a look, I was suppose to use base as variable but it is the keyword, so instead i used _base.
And I am using httpclient to in asp.net core 2.0 webapi and the code looks like this:
HttpClient client = new HttpClient();
if (client.BaseAddress == null)
{
client.BaseAddress = new Uri("https://api.cryptonator.com/");
}
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(baseUrl);
CurtoUsd usdrate = new CurtoUsd();
if (response.IsSuccessStatusCode)
{
usdrate = await response.Content.ReadAsJsonAsync<CurtoUsd>();
}
return CommonFunctions.ConvertDouble(usdrate.tick.price);
Detail
of function:
public static class HttpContentExtensions
{
public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
{
string json = await content.ReadAsStringAsync();
T value = JsonConvert.DeserializeObject<T>(json);
return value;
}
}
May I know what's wrong I am doing? Is the point I have pointed out correct, is there any solution if it is so.
Please help.
You can use # in C# to use keywords as identifiers, e.g. foo.#base.#class.
So your DTO becomes:
public class Ticker
{
public string #base { get; set; } // Escape the `base` keyword with `#`
public string target { get; set; }
public string price { get; set; }
public string volume { get; set; }
public string change { get; set; }
}
Note that you should use PascalCase for type identifiers n C#/.NET (so class Ticker instead of class ticker), and for public members too.
Note that Newtonsoft.Json is actually case-insensitive for member names by default (unless you specifically configure it otherwise) so you can use PascalCase for the properties, this also stops them from being C# keywords too, and it will still work:
public class Ticker
{
public string Base { get; set; } // `Base` is not a keyword
public string Target { get; set; }
public string Price { get; set; }
public string Volume { get; set; }
public string Change { get; set; }
}
I am trying to set a class for a token using DeserializeObject from the json object i get back from my api. However when i run the below code it sets all the values to null or 0, not the result i am getting from the api.
cs code
var resultString = await result.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<Token>(resultString);
class
public class Token : ContentPage
{
public int StaffID { get; set; }
public string TokenApi { get; set; }
public string StaffForename { get; set; }
public string StaffSurname { get; set; }
public string StaffEmail { get; set; }
public int PrimaryStaffRoleID { get; set; }
}
JSON response
"{\"code\":201,\"status\":\"Success\",\"message\":\"Object found\",\"data\":{\"StaffID\":14,\"StaffSurname\":\"Test\",\"StaffForename\":\"Test\",\"StaffEmail\":\"test#test.com\",\"PrimaryStaffRoleID\":5,\"TokenApi\":\"testToken\"}}"
Firstly the data which you are trying to map is inside another property in your json called Data and secondly your json does not have a property with name Token
The problem actually is you are not using the correct type that reflects your json, means you don't have correct c# type which would get mapped to json, you can generate correct types using json2charp.com , the correct classes for it are :
public class Data
{
public int StaffID { get; set; }
public string StaffSurname { get; set; }
public string StaffForename { get; set; }
public string StaffEmail { get; set; }
public int PrimaryStaffRoleID { get; set; }
public string TokenApi { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string status { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
Now deserializing using RootObject as type parameter would work perfectly fine like:
var resultString = await result.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<RootObject>(resultString);
A more good option is to use QuickType.IO which would even generate code for you in c# or any other language that they are supporting.
If you analyze the JSON that you posted, the object that you're trying to Deserialize is inside the "data" property of your json.
I suggest you creating a class to represent the JsonResponse with a Data property. This will be your Token
You are retrieved a string that match this object
public string code {get;set;}
public string Success {get;set;} ...
And Token is matching data in json, so
var post = JsonConvert.DeserializeObject<Token>(resultString.data);
would be better.
I am a beginner to C# programming. I understand the concepts of OOP as I know java. I have an assignment of building a desktop application that works similar to the CricBuzz website, i.e I am supposed to show live schedules and score of ongoing cricket matches.
I heard that there are APIs that do this for me. I found the API online but the issue is, I do not know how to implement or use APIs in my C# program. Please help me out here.
TIA. :)
Entities generated with json2csharp.
Using JavaScriptSerializer to deserialize json and a simple sequential WebClient call to download the json. You could improve on the quality and organization of this, try async, Newtonsoft.Json for serialization, etc. This is just a quick and dirty approach out of the many out there.
using System.Collections.Generic;
using JsSerializer = System.Web.Script.Serialization.JavaScriptSerializer;
using System.Net;
//
// http://cricapi.com/api/cricket/
//
namespace CricApi.Cricket
{
public class Provider
{
public string url { get; set; }
public string source { get; set; }
public string pubDate { get; set; }
}
public class Datum
{
public string title { get; set; }
public string description { get; set; }
public string unique_id { get; set; }
}
public class RootObject
{
public Provider provider { get; set; }
public List<Datum> data { get; set; }
public bool cache { get; set; }
}
}
//
//http://cricapi.com/api/cricketScore?unique_id=946981
//http://cricapi.com/api/cricketScore?unique_id=946765
//
namespace CricApi.CricketScore
{
public class Provider
{
public string pubDate { get; set; }
public string source { get; set; }
public string url { get; set; }
}
public class RootObject
{
public bool cache { get; set; }
public string inningsRequirement { get; set; }
public string team2 { get; set; }
public string team1 { get; set; }
public string score { get; set; }
public Provider provider { get; set; }
}
}
//
// how to use this
//
namespace CricApi
{
class Program
{
static void Main (string[] args)
{
WebClient client = new WebClient();
// Download cricket info
// dynamic dyn = JsonConvert.DeserializeObject(res);
string cricketJson = client.DownloadString("http://cricapi.com/api/cricket/");
Cricket.RootObject cro = new JsSerializer().Deserialize<Cricket.RootObject>(cricketJson);
// Download cricket score info
foreach (var datum in cro.data)
{
string uri = "http://cricapi.com/api/cricketScore?unique_id=" + datum.unique_id;
string cricketScoreJson = client.DownloadString(uri);
CricketScore.RootObject csro = new JsSerializer().Deserialize<CricketScore.RootObject>(cricketScoreJson);
}
}
}
}
I try to convert from json to c# class object, cause my final step will be put this all data into local db. I have no problem with taking this data like one big string, so the Url is good typed, but it's not my goal.
this is the json data, here we have two objects
[{"id":"1","category":"1","name":"good 1","prize":"12.3","prize2":"13.4","elements":"row,column,paper","secid":"2131","description":"nice","quality":"best","dateofcoming":"2013-12-20 18:08:50","date":"2013-12-20 00:00:00"},
{"id":"2","category":"2","name":"good","prize":"14.3","prize2":"15.4","elements":"up,down,left","secid":"2132","description":"nc","quality":"best","dateofcoming":"2013-12-20 18:10:55","date":"2013-12-20 00:00:00"}]
I try by this way which I found in the book:
private void getBookData()
{
// we creating the request details to the site which give us
// back the json data
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("here is my adress");
request.Accept = "and header";
// starting the request
request.BeginGetResponse(callback_with_food_info, request);
}
private void callback_with_food_info(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
// we get the response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(ListOfObjects));
Stream responseStream = response.GetResponseStream();
ListOfObjects listOfobj = (ListOfObjects)deserializer.ReadObject(responseStream);
String fsdfsdf = "how how how";
}
and in the row when we ReadObject
ListOfObjects listOfobj = (ListOfObjects)deserializer.ReadObject(responseStream);
I get exception "System.InvalidCastException", my List class look like this and it was created by http://json2csharp.com/
public class DetailsOfObject
{
public string id { get; set; }
public string category { get; set; }
public string name { get; set; }
public string prize { get; set; }
public string prize2 { get; set; }
public string elements { get; set; }
public string secid { get; set; }
public string description { get; set; }
public string quality { get; set; }
public string dateofcoming { get; set; }
public string date { get; set; }
}
public class ListOfObjects
{
public DetailsOfObject list {get; set;}
}
Any advice how to finally convert this json data
You need to add Data attributes to model
[DataContract]
public class DetailsOfObject
{
[DataMember]
public string id { get; set; }
and change deserialize line
List<DetailsOfObject> listOfobj = (List<DetailsOfObject>)deserializer.ReadObject(responseStream);
I made a call to a web server called Sample ApI. I want to be able to parse that data that's in json or xml, either would be nice and display it in a table format. This is what I have so far.
All I want is to be able to parse the data that's in this string _responseAsString and display a table. I don't know how to start it, I just know JavaScriptSerialzer parseXXX = new Java...lizer(). Please help me or assist in the right direction.
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_acknowledged { get; set; }
}
public ActionResult GetEvent()
{
try
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
System.IO.StreamReader _readResponse=new System.IO.StreamReader(response.GetResponseStream());
//The encrypted dynamics response in either xml or json
string _responseAsString=_readResponse.ReadToEnd();
JavaScriptSerializer parseResponse = new JavaScriptSerializer();
List<Event> events = parseResponse.Deserialize<List<Event>>(_responseAsString);
// this below is to make sure i was receiving my json data.
return Content(_responseAsString);
_readResponse.Close();
}
catch (Exception e)
{
//log error
}
return View();
}
This is the json data I receive when I make the http request:
"[{\"event_key\":\"cc2a1802-2b04-4530-ad50-0d4f0ed19dd3\",\"user_token\":\"40e62a11-40c4-408d-8cdd-1293cbaf9a41\",\"event_set_key\":\"615017f2-ae28-4b8d-9def-cf043642b928\",\"event_type\":\"Arrival\",\"event_date\":\"6/20/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"50fc1c22-d77b-4a91-b31d-da036827060b\",\"event_location_name\":\"Store2\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"True\"},{\"event_key\":\"2ac9e25e-137c-4a72-8cc5-157d67ea66c1\",\"user_token\":\"58cb4fcd-e140-4232-88c9-06eecb95b63d\",\"event_set_key\":\"00710ca7-f5d7-4c7a-bbfb-95491ae278ef\",\"event_type\":\"Arrival\",\"event_date\":\"9/23/2011
4:15:28
PM\",\"event_amount\":\"45\",\"event_location_key\":\"5a732dd5-9459-4cdd-a980-f3daf1a07343\",\"event_location_name\":\"Store4\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"},{\"event_key\":\"386b1fa1-11b2-48d9-b7f1-4bbe21ced487\",\"user_token\":\"c3d8b7ff-d85f-42a8-98f6-e091b48c2280\",\"event_set_key\":\"dc55843b-f8cf-4e8a-9091-188ce0609fe1\",\"event_type\":\"Arrival\",\"event_date\":\"9/18/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"be6d4fb4-c0e3-4303-b70d-7a22b721aa56\",\"event_location_name\":\"Store1\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"}]"
The JSON website has some good information on this.
For older browsers, you would eval the string (with some brackets to make it work):
var myObject = eval('(' + myJsonText + ')');
And these days, we tend to use
JSON.parse(myJsonText);
And server side, in C#
var serializer = new JavaScriptSerializer();
T obj = serializer.Deserialize<T>(myJsonText);
First of all...
If you're just passing through the JSON message returned from some other API, why not just return their response string verbatim (in other words, why deserialize it at all)?
public ActionResult GetEvent()
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
using (var readResponse= new StreamReader(response.GetResponseStream()))
{
return Content(readResponse.ReadToEnd(), "application/json");
}
}
Then read on
It's possible to use a JSON text reader to break apart the JSON message into a table of name/value pairs, but I think that's missing the point in your case. If the message is constant, just create a class that represents each element in the JSON message and parse it. I used json2csharp to stub such a class:
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_location_lat { get; set; }
public string event_location_long { get; set; }
public string event_description { get; set; }
public string event_acknowledged { get; set; }
}
Then use your favorite JSON serializer to deserialize into a list of these objects:
var serializer = new JavaScriptSerializer();
var events = serializer.Deserialize<List<Event>>(responseAsString);
(I prefer JSON.NET, here's the equivalent to the block above)
var events = JsonConvert.DeserializeObject<List<Event>>(responseAsString);
If you actually do need to be able to read a stream of text and generically create a table of name/value pairs, I'd use JSON.NET's LINQ-to-JSON or the JsonTextReader.