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).
Related
So basically I ran the JSON through jsonUtils which created an object, which turned out to be several objects.
So 2 questions please:
How to best populate objects from URL?
Can I select which objects to populate, i.e. I don't want to do all 20 objects?
In advance, thank you!!
WebClient client = new WebClient();
string myJSON = client.DownloadString("https://someURL.geojson");
var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);
Console.Write(myClass.ToString());
public class PrecipType
{
public string units { get; set; }
public string value { get; set; }
}
public class Press
{
public string units { get; set; }
public string value { get; set; }
}
public class Atmo
{
public AirTemperature air_temp{ get; set; }
public Dewpoint dew_point{ get; set; }
public Wind { get; set; }
public Pressure pressure { get; set; }
}
public class ObsTime
{
public string units { get; set; }
public string value { get; set; }
}
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.
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 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.
https://opendata.miamidade.gov/Corrections/Jail-Bookings-May-29-2015-to-current/7nhc-4yqn?
I don't if someone could help me with this: I've been having problems parsing/de-serializing the Address information that comes inside the Location object.
This is a fragment of the code i am using:
var results = dataset.Query<MiamiDade_JailLog>(soql);
public class MiamiDade_JailLog
{
public string chargecode3 { get; set; }
public string charge2 { get; set; }
public string bookdate { get; set; }
public string charge3 { get; set; }
public string chargecode1 { get; set; }
public string chargecode2 { get; set; }
public string charge1 { get; set; }
public string dob { get; set; }
public Location1 location_1 { get; set; }
public string defendant { get; set; }
}
public class Location1
{
public bool needs_recoding { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
public HumanAddress human_address { get; set; }
}
public class HumanAddress
{
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
}
and this is the error message:
Error converting value
"{"address":"HOMELESS","city":"MIAMI","state":"FL","zip":""}" to type
'JailLog_WFA.HumanAddress'. Path 'location_1.human_address', line 1,
position 424.
This is the response I got from Socrata:
If you look at this json response, https://opendata.miamidade.gov/resource/7nhc-4yqn.json
You'll see that for the location_1 column, we provide an object, {}
and then within there you'll see human_address which we provide as a string "" instead of as an object.
For JavaScript, it would just be JSON.parse("{\"address\":\"17725 NW 8TH PL\",\"city\":\"MIAMI GARDENS\",\"state\":\"FL\",\"zip\":\"33169\"}");
From the code you sent, it looks like you are treating HumanAddress as an object instead of as a string that needs to be parsed into an object.
If you make this change it should work.
...And this was my response:
You gave me very good info. However I had already done a workaround to parse the object.
I just removed the extra quotes from the human_ address object and was able to parse everything at once.