Have this service built on a xamarin app:
public class OpenWeatherMap<T>
{
private const string OpenWeatherApi = "http://api.openweathermap.org/data/2.5/weather?q=";
private const string Key = "653b1f0bf8a08686ac505ef6f05b94c2";
HttpClient _httpClient = new HttpClient();
// aqui podemos enviar directo a una ciudad hardcoded
public async Task<T> GetAllWeathers(string city)
{
var json = await _httpClient.GetStringAsync(OpenWeatherApi + city + "&APPID=" + Key);
var getWeatherModels = JsonConvert.DeserializeObject<T>(json);
return getWeatherModels;
}
}
When i check the model object is always empty. JSON is fine and my class matches perfectly my JSON model. I'm using Newtonsoft.Json.
This is my model:
public class WeatherMainModel
{
[JsonProperty("coord")]
public Coord Coord { get; set; }
[JsonProperty("weather")]
public WeatherSubDetails[] Weather { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("main")]
public Main Main { get; set; }
[JsonProperty("visibility")]
public string Visibility { get; set; }
[JsonProperty("wind")]
public WeatherWindDetails Wind { get; set; }
[JsonProperty("clouds")]
public Clouds Clouds { get; set; }
[JsonProperty("dt")]
public string Dt { get; set; }
[JsonProperty("sys")]
public WeatherSysDetails Sys { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cod")]
public string Cod { get; set; }
}
public partial class Clouds // new
{
[JsonProperty("all")]
public string All { get; set; }
}
public partial class Coord // new
{
[JsonProperty("lon")]
public string Lon { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
}
public partial class Main
{
[JsonProperty("temp")]
public string Temp { get; set; }
[JsonProperty("pressure")]
public string Pressure { get; set; }
[JsonProperty("humidity")]
public string Humidity { get; set; }
[JsonProperty("temp_min")]
public string TempMin { get; set; }
[JsonProperty("temp_max")]
public string TempMax { get; set; }
}
public partial class WeatherSysDetails
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("sunrise")]
public string Sunrise { get; set; }
[JsonProperty("sunset")]
public string Sunset { get; set; }
}
public partial class WeatherSubDetails
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("main")]
public string Main { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
}
public partial class WeatherWindDetails
{
[JsonProperty("speed")]
public string Speed { get; set; }
[JsonProperty("deg")]
public string Deg { get; set; }
}
I'm using visual studio community set for Latin America (Chile), so i tried changing every decimal field on the JSON to string on the model to avoid comma separation problems, but still, my object is coming empty no matter the JSON i inject to the deserializer.
Thanks in advance.
Related
I need your help.
UIViewControl....
var data= await track.QueryCategory(link);
if(data!=null)
{
var get_data=JsonConvert.DeserializeObject<Categorycs.RootObject>(data);
_table = new UITableView {
Frame = new CoreGraphics.CGRect (0, 0, View.Bounds.Width, View.Bounds.Height),
Source= new TableSoundCloudSource(get_data.tracks)
};
View.AddSubview (_table);
}
TableSource.cs
public class TableSource: UITableViewSource
{
List<string> tableItems;
string cellIdentifier="TableCell";
public TableSource (List<string> items)
{
tableItems = items;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return tableItems;
}
public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier);
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier);
} else
cell.TextLabel.Text = tableItems [indexPath.Row];
return cell;
}
}
}
Public class Categorycs
{
public class RootObject
{
public List<Track> tracks { get; set; }
public string tag { get; set; }
public string next_href { get; set; }
}
}
public class Track
{
public string urn { get; set; }
public string uri { get; set; }
public string permalink { get; set; }
public string permalink_url { get; set; }
public string title { get; set; }
public string description { get; set; }
public string track_type { get; set; }
public string genre { get; set; }
public string tag_list { get; set; }
public int duration { get; set; }
public bool? downloadable { get; set; }
public string download_url { get; set; }
public int original_content_size { get; set; }
public bool streamable { get; set; }
public bool commentable { get; set; }
public string sharing { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string isrc { get; set; }
public string state { get; set; }
public int? likes_count { get; set; }
public int? playback_count { get; set; }
public int? reposts_count { get; set; }
public int? download_count { get; set; }
public int? comment_count { get; set; }
public string embeddable_by { get; set; }
public string license { get; set; }
public string artwork_url { get; set; }
public string stream_url { get; set; }
public string waveform_url { get; set; }
public string purchase_url { get; set; }
public string purchase_title { get; set; }
public bool reveal_comments { get; set; }
public bool reveal_stats { get; set; }
public bool feedable { get; set; }
public bool geo_blocking { get; set; }
public object geo_blockings { get; set; }
public bool embeddable { get; set; }
public string label_name { get; set; }
public string release_date { get; set; }
public object schedule { get; set; }
public Visuals visuals { get; set; }
public object publisher_metadata { get; set; }
public object monetization { get; set; }
public int user_id { get; set; }
public User user { get; set; }
public string policy { get; set; }
public string monetization_model { get; set; }
public object secret_token { get; set; }
public object secret_uri { get; set; }
public object publisher_state { get; set; }
public string last_modified { get; set; }
public object disabled_at { get; set; }
public object disabled_reason { get; set; }
public bool has_downloads_left { get; set; }
public string kind { get; set; }
public int id { get; set; }
}
Errors:Error CS1503: Argument #1' cannot
convertSystem.Collections.Generic.List<'Categorycs.Track'>' expression
to type `string[]'.
I have try to replaced 'List<'string'>'to List<'Categorycs.Track'> but app don't run.
here, you are passing TableSource get_data.tracks, which is a List<Track>:
Source= new TableSoundCloudSource(get_data.tracks)
but here, you are telling TableSource to accept a List<string>
public TableSource (List<string> items)
this is a "type mismatch" - it is expecting an object of Type A, but you are passing it an object of Type B. In some cases it can automatically convert A to B, but not in this case.
(I'm assuming that the fact that it is named "TableSoundCloudSource" in one place and "TableSource" in another is a cut-and-paste error. If not, then that is another problem with your code.)
You either need to modify your TableSource to accept a List<Track> (which will require several changes) or you need to pass it a List<string>, which is what it currently expects.
The 2nd error you're reporting is because of this:
public override nint RowsInSection(UITableView tableview, nint section)
{
return tableItems;
}
that function should return an nint, but you are returning tableItems, which is a List (it doesn't really matter what kind of list). What you really want to return is tableItems.Count, which is the number of elements in your list.
This code was always wrong, but because of the earlier problem the compiler probably never got to it to tell you it was bad. Debugging is like this - fixing one bug can uncover (or create) several more. You just have to slog through them until it works.
Finally,
cell.TextLabel.Text = tableItems [indexPath.Row];
Text is a string, tableItems[indexPath.Row] is a Track. You can't assign a Track to a string - that's another type mismatch. Instead, do this
cell.TextLabel.Text = tableItems [indexPath.Row].title;
Since the title property of Track is a string, that works (I'm assuming you want to use title - you can use any property that is a string, or can be automatically converted to a string)
Note that this really has nothing to do with Xamarin - it's basic C#, and conceptually basic programming.
get links will be like this - http//192.156.120.192/Projects/cricket/index.php/api/api
public class Player
{
public int playerId { get; set; }
public string playerName { get; set; }
public string specialization { get; set; }
public string battingHand { get; set; }
public string bowlingHand { get; set; }
public string bowlingType { get; set; }
public object genericId { get; set; }
public int homeTeamId { get; set; }
public int eligibleTeams { get; set; }
public object imageUrl { get; set; }
}
public class RootObject
{
public string methodName { get; set; }
public int errorCode { get; set; }
public string errorMessage { get; set; }
public List<Player> players { get; set; }
}
I am using Json.NET and it is super easy
// create a RootObject object
//..
string serializedRoot = JsonConvert.SerializeObject(myRootObject);
RootObject deserializedRoot = JsonConvert.DeserializeObject<Player>(serializedRoot);
The first JSON is look like this
The second JSON is look like this
How can I deserialize them? I have been follow this example but it's not working.
Here's my code.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var w = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized =
JsonConvert.DeserializeObject<List<Place>>(r.EventArgs.Result);
PlaceList.ItemsSource = deserialized;
});
w.DownloadStringAsync(
new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place"));
//For 2nd JSON
//w.DownloadStringAsync(
//new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place/243"));
}
These are classes for 1st JSON.
public class Place
{
public string id { get; set; }
public string title { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
}
public class RootObjectJSON1
{
public List<Place> Places { get; set; }
}
These are classes for JSON2
public class Address
{
public string street { get; set; }
public string postal_code { get; set; }
public string post_office { get; set; }
}
public class Image
{
public string id { get; set; }
public string filename { get; set; }
public string path { get; set; }
}
public class RootObjectJSON2
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string contact_person { get; set; }
public Address address { get; set; }
public List<Image> images { get; set; }
}
it looks that you should be deserializing object RootObjectJSON1 or RootObjectJSON2, e.g.:
var deserialized = JsonConvert.DeserializeObject<RootObjectJSON1>(r.EventArgs.Result);
Also it seems that collection Places should be with lowercase p at beginning or you need to tell Json.NET that this property should be deserialized with different name, e.g.:
[JsonProperty(PropertyName="places")]
public List<Place> Places { get; set; }
Generally I tend to use arrays for deserialization (from my experience works better) so I'll suggest to rewrite it to this:
public class RootObjectJSON1
{
public Place[] places { get; set; }
}
There is very good tool named json2csharp available at http://json2csharp.com/ - just put sample of JSON there and it will spit out classes in C# (doesn't detect DateTime so you might need to change that).
I've this code through which I am retrieveing json data from my Localhost.But it is giving the error mentioned in my title.When I hover over the response while debugging.It shows me the correct response.I am using JSON.NET to parse json response.
var response = reader.ReadToEnd();
List<Company> cLst = JsonConvert.DeserializeObject<List<Company>>(response); //Error
this.Dispatcher.BeginInvoke(() =>
{
foreach (Company c in cLst)
{
ListBoxItemControl Li = new ListBoxItemControl();
Li.CompanyNameTextBlock.Text = c.CompanyName;
Li.PromotionTextBlock.Text = c.PromotionText;
listBox1.Items.Add(Li);
}
});
Here is the Company Class.
class Company
{
public string CompanyName {get; set;}
public string CompanySlogan { get; set; }
public string CompanyDescription { get; set; }
public string CompanyRating { get; set; }
public string CompanyDpPath { get; set; }
public string CompanyOtherInfo { get; set; }
public string CompanyFollowers { get; set; }
public int CompanyID { get; set; }
public int PromotionID { get; set; }
public string PromotionText { get; set; }
public string PromotionRating { get; set; }
public string PromotionPicPath { get; set; }
public string PromotionTitle { get; set; }
public int PromotionLikes { get; set; }
public int PromotionComments { get; set; }
}
Try making the Company class public
Take another class like,
public class RootObject
{
public List<Company> companies;
}
And then modify your code like this,
var jsonData = JsonConvert.DeserializeObject<RootObject>(response);
List<Company> cLst = jsonData.companies;
Try this and let me know.
I'm having some trouble binding this json to a ListBox...The problem seems to happen in the ActivityTrack class/object of the JSON...i'm not sure what is not meshing...
{"collection":[{"type":"track","created_at":"2011/09/18 14:04:00 +0000","origin":{"id":23606164,"created_at":"2011/09/18 14:03:59 +0000","user_id":222927,"duration":342465,"commentable":true,"state":"finished","sharing":"public","tag_list":"garage usgarage soulfulhouse house deephouse deep","permalink":"pablo-cortez-when-i-need-u","description":"","streamable":true,"downloadable":false,"genre":"UK Garage","release":"","purchase_url":null,"label_id":null,"label_name":"","isrc":"","video_url":null,"track_type":"demo","key_signature":"","bpm":null,"title":"Pablo Cortez - When I Need U (Back To 90s Mix)","release_year":null,"release_month":null,"release_day":null,"original_format":"mp3","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/23606164","permalink_url":"http://soundcloud.com/pablocortez/pablo-cortez-when-i-need-u","artwork_url":null,"waveform_url":"http://w1.sndcdn.com/wuiZilHRZhl6_m.png","user":{"id":222927,"permalink":"pablocortez","username":"Pablo Cortez","uri":"https://api.soundcloud.com/users/222927","permalink_url":"http://soundcloud.com/pablocortez","avatar_url":"http://i1.sndcdn.com/avatars-000000771958-y059w8-large.jpg?ca13f03"},"stream_url":"https://api.soundcloud.com/tracks/23606164/stream","user_playback_count":1,"user_favorite":false,"playback_count":28,"download_count":0,"favoritings_count":0,"comment_count":2,"attachments_uri":"https://api.soundcloud.com/tracks/23606164/attachments","sharing_note":{"text":"My new sounds","created_at":"2011/09/18 14:03:59 +0000"}},"tags":"affiliated"}],"next_href":"https://api.soundcloud.com/me/activities/track.json?cursor=86db5e5e-e1fe-11e0-9c69-0f0dad493cfc\\u0026limit=1","future_href":"https://api.soundcloud.com/me/activities/track?uuid%5Bto%5D=2d9c67ee-e22f-11e0-94fa-45aa16adeba3"}
Here is the class structure which i am trying to bind the JSON too
public class Activities
{
public ActivityTrack [] activities { get; set; }
public string next_href { get; set; }
public string future_href { get; set; }
}
public class ActivityTrack
{
public string type { get; set; }
public string created_at { get; set; }
public OriginActivityTrack origin { get; set; }
public string tags { get; set; }
}
public class OriginActivityTrack
{
public string id { get; set; }
public string created_at { get; set; }
public string user_id { get; set; }
public string duration { get; set; }
public string commentable { get; set; }
public string state { get; set; }
public string sharing { get; set; }
public string tag_list { get; set; }
public string permalink { get; set; }
public string description { get; set; }
public string streamable { get; set; }
public string downloadable { get; set; }
public string genre { get; set; }
public string release { get; set; }
public string purchase_url { get; set; }
public string label_id { get; set; }
public string label_name { get; set; }
public string isrc { get; set; }
public string video_url { get; set; }
public string track_type { get; set; }
public string key_signature { get; set; }
public string bpm { get; set; }
public string title { get; set; }
public string release_year { get; set; }
public string release_month { get; set; }
public string release_day { get; set; }
public string original_format { get; set; }
public string license { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string artwork_url { get; set; }
public string waveform_url { get; set; }
public SmallUser user { get; set; }
public string stream_url { get; set; }
public string user_playback_count { get; set; }
public string user_favorite { get; set; }
public string playback_count { get; set; }
public string download_count { get; set; }
public string favoritings_count { get; set; }
public string comment_count { get; set; }
public string attachments_uri { get; set; }
public SharingNote sharing_note;
}
public class SharingNote
{
public string text { get; set; }
public string created_at { get; set; }
}
public class SmallUser
{
public string id { get; set; }
public string permalink { get; set; }
public string username { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string avatar_url { get; set; }
}
This is the current code for binding to listbox:
private void ReadCallbackDashboard(IAsyncResult asynchronousResult)
{
lock (locker)
{
try
{
HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 =
new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(resultString)))
{
if (ms != null)
{
var ser = new DataContractJsonSerializer(typeof(Activities));
Activities obj = (Activities)ser.ReadObject(ms);
userDashboardActivities = null;
userDashboardActivities = new ObservableCollection<ActivityTrack>();
for (int i = 0; i < obj.activities.Length; ++i)
{
userDashboardActivities.Add(obj.activities[i]);
}
if (userDashboardActivities.Count() == 0)
{
messageDashboard = "No Tracks Found";
UIThread.Invoke(() => mainMessage.Text = messageDashboard);
}
else
{
messageDashboard = "";
UIThread.Invoke(() => mainMessage.Text = messageDashboard);
UIThread.Invoke(() => dashboardBox.ItemsSource = userDashboardActivities);
}
}
}
}
}
catch (WebException we)
{
UIThread.Invoke(() => MessageBox.Show("Could not retrieve the latest. Internet down? Try a refresh."));
}
}
}
please check it out! Thanks in advance!
Answer as discovered in the comments.
You have called your property activities but the json calls it collection.