Regarding google places API - c#

What I want to know is that using Google places API. Basically I want to create a site like www.zomato.com
1) Can I show listing of all restaurants and their individual details with all the details in my city just like Google+ business page?
2) Is is possible to use this API with C#.net?
3) How much Google will charge for this?

If we look at the documentation for the Google Places API, we can see the format of the JSON that a request to the API returns. By using json2csharp, we can then easily generate a C# model for the response to a Google Places query.
public class Location
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Geometry
{
public Location location { get; set; }
}
public class OpeningHours
{
public bool open_now { get; set; }
public List<object> weekday_text { get; set; }
}
public class Photo
{
public int height { get; set; }
public List<string> html_attributions { get; set; }
public string photo_reference { get; set; }
public int width { get; set; }
}
public class Result
{
public Geometry geometry { get; set; }
public string icon { get; set; }
public string id { get; set; }
public string name { get; set; }
public OpeningHours opening_hours { get; set; }
public List<Photo> photos { get; set; }
public string place_id { get; set; }
public double rating { get; set; }
public string reference { get; set; }
public string scope { get; set; }
public List<string> types { get; set; }
public string vicinity { get; set; }
}
public class PlacesApiQueryResponse
{
public List<object> html_attributions { get; set; }
public List<Result> results { get; set; }
public string status { get; set; }
}
With a simple HTTP request to the Google Places API, we can then deserialize the query results using Json.NET.
using (var client = new HttpClient())
{
var response = await client.GetStringAsync(string.Format("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={0},{1}&radius=500&type=bar&key=YourAPIKey", latitude, longitude));
var result = JsonConvert.DeserializeObject<PlacesApiQueryResponse>(response);
}

Related

C# Getting individual data from JSON text downloaded from a site

I've been searching around for a long while for this, I haven't found any solutions to my issue which is:
I've been trying get a json data individually from a whole source seen here:
{"TargetId":0,"ProductType":null,"AssetId":1239281845,"ProductId":0,"Name":"❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack","Description":"Shirt Image","AssetTypeId":1,"Creator":{"Id":124026176,"Name":"TheDestroyerPeter","CreatorType":"User","CreatorTargetId":124026176},"IconImageAssetId":0,"Created":"2017-12-12T19:48:24.693Z","Updated":"2017-12-12T19:48:24.693Z","PriceInRobux":null,"PriceInTickets":null,"Sales":0,"IsNew":false,"IsForSale":false,"IsPublicDomain":false,"IsLimited":false,"IsLimitedUnique":false,"Remaining":null,"MinimumMembershipLevel":0,"ContentRatingTypeId":0}
now what I've been trying to do with it is get the Product Name using C# and the product name is "❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack", my issue is that I haven't found a way to extract the data, and when I have I haven't been able to get the right data, because instead if gives me "TheDestroyerPeter"
I've written up code, and deleted it, it was really sloppy and it would take awhile to rewrite, I appreciate any solutions
-whoever I am
You can use JavaScriptSerializer class, which is part of the System.Web.Script namespace.
For example :
var jsonString = #"{""name"":""John Doe"",""age"":20}";
var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonString );
and then JSONObj["name"]; gives you "John Doe"
in this case you can use it :
public class Creator
{
public int Id { get; set; }
public string Name { get; set; }
public string CreatorType { get; set; }
public int CreatorTargetId { get; set; }
}
public class RootObject
{
public int TargetId { get; set; }
public object ProductType { get; set; }
public int AssetId { get; set; }
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int AssetTypeId { get; set; }
public Creator Creator { get; set; }
public int IconImageAssetId { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public object PriceInRobux { get; set; }
public object PriceInTickets { get; set; }
public int Sales { get; set; }
public bool IsNew { get; set; }
public bool IsForSale { get; set; }
public bool IsPublicDomain { get; set; }
public bool IsLimited { get; set; }
public bool IsLimitedUnique { get; set; }
public object Remaining { get; set; }
public int MinimumMembershipLevel { get; set; }
public int ContentRatingTypeId { get; set; }
}
use Newtonsoft.Json
var jsonString = #"{""TargetId"":0,""ProductType"":null,""AssetId"":1239281845,""ProductId"":0,""Name"":""❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack"",""Description"":""Shirt Image"",""AssetTypeId"":1,""Creator"":{""Id"":124026176,""Name"":""TheDestroyerPeter"",""CreatorType"":""User"",""CreatorTargetId"":124026176},""IconImageAssetId"":0,""Created"":""2017-12-12T19:48:24.693Z"",""Updated"":""2017-12-12T19:48:24.693Z"",""PriceInRobux"":null,""PriceInTickets"":null,""Sales"":0,""IsNew"":false,""IsForSale"":false,""IsPublicDomain"":false,""IsLimited"":false,""IsLimitedUnique"":false,""Remaining"":null,""MinimumMembershipLevel"":0,""ContentRatingTypeId"":0}";
var obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine(obj.Creator.Name); //"TheDestroyerPeter"

Obtaining YouTube Statistics Using JSON (UWP, C#)

been a while since I posted here. I'm working on an app and need to fetch statistics for a particular video using JSON (C#, UWP).
I already have the statistics as a JSON string but can't seem to parse them properly using Newtonsoft. The value always comes back null. This is my code:
var url = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + cl.googleAPIKey + "&part=snippet,contentDetails,statistics,status";
var http = new HttpClient();
var response = await http.GetStringAsync(url);
var statistics = JsonConvert.DeserializeObject<Statistics>(response);
string totalViews = statistics.viewCount;
The classes generated by Json2CSharp are:
public class PageInfo
{
public int totalResults { get; set; }
public int resultsPerPage { get; set; }
}
public class Default
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Medium
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class High
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Standard
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Maxres
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Thumbnails
{
public Default #default { get; set; }
public Medium medium { get; set; }
public High high { get; set; }
public Standard standard { get; set; }
public Maxres maxres { get; set; }
}
public class Localized
{
public string title { get; set; }
public string description { get; set; }
}
public class Snippet
{
public DateTime publishedAt { get; set; }
public string channelId { get; set; }
public string title { get; set; }
public string description { get; set; }
public Thumbnails thumbnails { get; set; }
public string channelTitle { get; set; }
public List<string> tags { get; set; }
public string categoryId { get; set; }
public string liveBroadcastContent { get; set; }
public Localized localized { get; set; }
}
public class ContentDetails
{
public string duration { get; set; }
public string dimension { get; set; }
public string definition { get; set; }
public string caption { get; set; }
public bool licensedContent { get; set; }
public string projection { get; set; }
}
public class Status
{
public string uploadStatus { get; set; }
public string privacyStatus { get; set; }
public string license { get; set; }
public bool embeddable { get; set; }
public bool publicStatsViewable { get; set; }
}
public class Statistics
{
public string viewCount { get; set; }
public string likeCount { get; set; }
public string dislikeCount { get; set; }
public string favoriteCount { get; set; }
public string commentCount { get; set; }
}
public class Item
{
public string kind { get; set; }
public string etag { get; set; }
public string id { get; set; }
public Snippet snippet { get; set; }
public ContentDetails contentDetails { get; set; }
public Status status { get; set; }
public Statistics statistics { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public string etag { get; set; }
public PageInfo pageInfo { get; set; }
public List<Item> items { get; set; }
}
As I say the value will always come back as null regardless of the video ID.
Does anyone have any ideas?
Thanks
You are deserializing to the wrong class. Json2Csharp generated many classes, but Statistics is way down the tree. You should deserialize the RootObject instead:
var root = JsonConvert.DeserializeObject<RootObject>( response );
And then navigate to the statistics within the resulting class structure like for example:
foreach ( var statistics in root.Items.Select( i => i.Statistics) )
{
//do something
}

Working with JSON from the AWS SDK Pricing API

I'm trying to work with AWS SDK in C# to follow and update a price catalog.
I'm using the method GetProductsAsync to list EC2 products for example, I then try to deserialize the response.
I use Json.Net to deserialize my response into a class I created using the "Paste JSON as classes" function from Visual Studio.
The object is somewhat populated, but the pricing model follows a weird JSON pattern.
Here is an extract of the object:
"terms":{
"OnDemand":{
"FBKCX9C4KX8NSVN3.JRTCKXETXF":{
"priceDimensions":{
"FBKCX9C4KX8NSVN3.JRTCKXETXF.6YS6EN2CT7":{
"unit":"Hrs",
"endRange":"Inf",
"description":"$2.47 per On Demand RHEL m4.10xlarge Instance Hour",
"appliesTo":[
],
"rateCode":"FBKCX9C4KX8NSVN3.JRTCKXETXF.6YS6EN2CT7",
"beginRange":"0",
"pricePerUnit":{
"USD":"2.4700000000"
}
}
},
The IDs under OnDemand and PriceDimensions seem to be references to other objects; therefore, they are not populated when I deserialize the JSON object, as they are different per product type.
Has anyone succeeded in getting pricing information for AWS assets?
For JSON objects having keys which can vary, you can use a Dictionary<string, T> in place of a regular class, where T is a class representing the item data. So in your case, you'd need a dictionary for both OnDemand and priceDimensions. The resulting class definitions would look like this:
public class OuterObject
{
public Terms terms { get; set; }
}
public class Terms
{
public Dictionary<string, OnDemandItem> OnDemand { get; set; }
}
public class OnDemandItem
{
public Dictionary<string, PriceDimensionsItem> priceDimensions { get; set; }
}
public class PriceDimensionsItem
{
public string unit { get; set; }
public string endRange { get; set; }
public string description { get; set; }
public object[] appliesTo { get; set; }
public string rateCode { get; set; }
public string beginRange { get; set; }
public PricePerUnit pricePerUnit { get; set; }
}
public class PricePerUnit
{
public string USD { get; set; }
}
Demo: https://dotnetfiddle.net/dJ5jmQ
Note: you could also use a Dictionary<string, string> in place of the PricePerUnit class if you will be dealing with a lot of different currencies. If there will just one or two, then having a strongly-typed class with properties for each possible currency will work fine. For example, you could add a property public string EUR { get; set; } to handle Euro.
AWS SDK have one more "level" after OnDemand.
I made my own class based on Brian Rogers answer, and i add the rest of the class to support Reserved and Products, making a nested class.
public class OuterObject
{
public Dictionary<string, Products> products { get; set; }
public Terms terms { get; set; }
}
public class Products
{
public string sku { get; set; }
public string productFamily { get; set; }
public Attributes attributes { get; set; }
}
public class Attributes
{
public string servicecode { get; set; }
public string location { get; set; }
public string locationType { get; set; }
public string instanceType { get; set; }
public string currentGeneration { get; set; }
public string vcpu { get; set; }
public string memory { get; set; }
public string operatingSystem { get; set; }
public string licenseModel { get; set; }
public string preInstalledSw { get; set; }
public string tenancy { get; set; }
}
public class Terms
{
public Dictionary<string, Dictionary<string, OnDemandItem>> OnDemand { get; set; }
public Dictionary<string, Dictionary<string, OnDemandItem>> Reserved { get; set; }
}
public class OnDemandItem
{
public string offerTermCode { get; set; }
public string sku { get; set; }
public Dictionary<string, PriceDimensionsItem> priceDimensions { get; set; }
public TermAttributes termAttributes { get; set; }
}
public class PriceDimensionsItem
{
public string unit { get; set; }
public string endRange { get; set; }
public string description { get; set; }
public object[] appliesTo { get; set; }
public string rateCode { get; set; }
public string beginRange { get; set; }
public PricePerUnit pricePerUnit { get; set; }
}
public class PricePerUnit
{
public string USD { get; set; }
}
public class TermAttributes
{
public string LeaseContractLength { get; set; }
public string OfferingClass { get; set; }
public string PurchaseOption { get; set; }
}

Deserialize JSON of an unknown type (Google Map API)

I'm trying to work with the google maps api. This URL is EXACTLY what I need:
http://maps.googleapis.com/maps/api/geocode/json?address=77379
Take a look at the results. It has all the info I need... lat, lon, state, country. Trouble is, I don't know how to extract this data. I tried this:
var client = new WebClient();
var content = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address=77379");
object myObject = JsonConvert.DeserializeObject(content);
While that doesn't error out, myObject doesn't end up being anything useful. (Or, maybe it is and I just don't know it?)
Here is your class structure
public class AddressComponent
{
public string long_name { get; set; }
public string short_name { get; set; }
public List<string> types { get; set; }
}
public class Northeast
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Southwest
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Bounds
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public class Location
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Northeast2
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Southwest2
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Viewport
{
public Northeast2 northeast { get; set; }
public Southwest2 southwest { get; set; }
}
public class Geometry
{
public Bounds bounds { get; set; }
public Location location { get; set; }
public string location_type { get; set; }
public Viewport viewport { get; set; }
}
public class Result
{
public List<AddressComponent> address_components { get; set; }
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public string place_id { get; set; }
public List<string> postcode_localities { get; set; }
public List<string> types { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
public string status { get; set; }
}
And you have to do
RootObject rootObject = new JavaScriptSerializer().Deserialize<RootObject>(content);
Try referring to this stackoverflow posting if you would prefer other ways
Deserialize JSON with C#
From my experience using JSON I have always used this method:
object myObject = JsonConvert.DeserializeObject(content);
Would that work? Or is this something different from what you're doing?

XML Deserializing with Lists

I am using webclient to deserialize XML content from a webservice:
var serializer = new XmlSerializer(typeof(SearchArticles), new XmlRootAttribute("search_articles"));
var results = (SearchArticles)serializer.Deserialize(response.Content.ReadAsStreamAsync().Result);
The xml content is like:
<?xml version=\"1.0\" encoding=\"UTF-8\"?><search_articles><articles hits=\"10134\"><article><id>1763794</id>...
My Models look like:
public class SearchArticles
{
[XmlElement("articles")]
public ArticleHelper articles { get; set; }
}
public class ArticleHelper
{
[XmlAttribute("hits")]
public long hits { get; set; }
[XmlElement("article")]
public List<Article> articles { get; set; }
}
public class Article
{
public long id { get; set; }
public string partner { get; set; }
public string number { get; set; }
public long number_is_generated { get; set; }
public string status { get; set; }
public long company_id { get; set; }
}
This is working, but how can I avoid having the ArticleHelper ?
You can remove ArticleHelper by modifying SearchArticles and Article as:
public class SearchArticles
{
[XmlArray("articles")]
[XmlArrayItem("article", Type = typeof(Article))]
public List<Article> articles { get; set; }
}
public class Article
{
public long id { get; set; }
public string partner { get; set; }
public string number { get; set; }
public long number_is_generated { get; set; }
public string status { get; set; }
public long company_id { get; set; }
}
However, you lose access the hits attribute value.

Categories