I can't load data from json to tableview on xamarin - json

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.

Related

How to parse json with object and List for the same attribute? C#

On trying to parse JSON, I got an error about types. I have this code:
public class Event
{
[JsonProperty("eventKey")]
public int EventKey { get; set; }
[JsonProperty("displayOrder")]
public int DisplayOrder { get; set; }
[JsonProperty("subTypeKey")]
public int SubTypeKey { get; set; }
[JsonProperty("eventName")]
public string EventName { get; set; }
[JsonProperty("eventNameTranslated")]
public string EventNameTranslated { get; set; }
[JsonProperty("eventStatus")]
public string EventStatus { get; set; }
[JsonProperty("eventSort")]
public string EventSort { get; set; }
[JsonProperty("eventDateTime")]
public DateTime EventDateTime { get; set; }
[JsonProperty("classSortCode")]
public string ClassSortCode { get; set; }
[JsonProperty("typeFlagCode")]
public string TypeFlagCode { get; set; }
}
public class Events
{
[JsonProperty("num")]
public int Num { get; set; }
[JsonProperty("event")]
public IList<Event> Event { get; set; }
}
public class Subtype
{
[JsonProperty("subTypeKey")]
public int SubTypeKey { get; set; }
[JsonProperty("subTypeName")]
public string SubTypeName { get; set; }
[JsonProperty("displayOrder")]
public int DisplayOrder { get; set; }
[JsonProperty("events")]
public Events Events { get; set; }
}
public class Subtypes
{
[JsonProperty("num")]
public int Num { get; set; }
[JsonProperty("subtype")]
public Subtype Subtype { get; set; }
}
But I am getting error, because it can't parse it, cause sometimes it have type as List, sometimes as object. See screenshot (subtype and event).
How can I change my code to support different types?
Can you help me with this? Or what I need to read, to solve my problem?

Trying to check a json file for the correct parameters using JsonConvert.DeserisalizeObject<t>

I'm using the ACE code editor to gather Json and send it to my application. Once the Json hits the application, I need to make sure there are certain key's inside the json so I am using JsonConvert.DeserisalizeObject<t> to do this. Here's how:
public void SubmitReport(string JsonStringSend)
{
try
{
ReportItem RptItem = JsonConvert.DeserializeObject<ReportItem>(JsonStringSend);
}
catch(err)
{
return View(err);
}
}
and:
public class ReportItem
{
public Guid ReportID;
public bool RequiresFilter;
public string MimeType { get; set; }
public string ExternalID { get; set; }
public DateTime CreatedBy { get; set; }
public string ExecutionScript { get; set; }
public string ExecutionParameter { get; set; }
public string ExecutionOrderBy { get; set; }
public List<DynamicFilter> DynamicFilters { get; set; }
public bool RequiresOrgID { get; set; }
public QueryFilter ReportFilter { get; set; }
public QueryRule ReportRules { get; set; }
public List<QueryColumn> Columns { get; set; }
}
But for some reason, it bounces right over the catch even when I make sure some of the key's are incorrect. Am I not understanding the correct usage JsonConvert.DeserisalizeObject<t>? Or, is there a better way to be doing this check?
By default, the deserializer "tries it's best" to deserialize the object. But JSon.NET supports validation, the "straightforward" way is probably JSon Schema: http://www.newtonsoft.com/jsonschema.
Simple case can be handled with JSon.NET directly:
public class ReportItem
{
[JsonProperty(Required = Required.Always)]
public bool RequiresFilter;
[JsonProperty(Required = Required.Always)]
public string MimeType { get; set; }
public DateTime CreatedBy { get; set; }
public string ExecutionScript { get; set; }
public string ExecutionParameter { get; set; }
public string ExecutionOrderBy { get; set; }
public bool RequiresOrgID { get; set; }
}

I am a new bee with JSON and I don't know how to perform serialization and deserialization in windows phone

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);

How can I deserialization JSON in Windows Phone?

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).

Attempt to access the method failed: System.Collections.Generic.List`1..ctor()

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.