Deserialized problem GetJsonAsync<T> with Flurl - flurl

I want to parse JSON to list with Flurl. My JSON data like this.
{
"api": {
"results": 114,
"fixtures": {
"195": {
"fixture_id": "195",
"event_timestamp": "1543759500",
"event_date": "2018-12-02T14:05:00+00:00",
"league_id": "2",
"round": "Premier League - 14",
"homeTeam_id": "42",
"awayTeam_id": "47",
"homeTeam": "Arsenal",
"awayTeam": "Tottenham",
"status": "Match Finished",
"statusShort": "FT",
"goalsHomeTeam": "4",
"goalsAwayTeam": "2",
"halftime_score": "1 - 2",
"final_score": "4 - 2",
"penalty": null,
"elapsed": "87",
"firstHalfStart": "1543759500",
"secondHalfStart": "1543763100"
}
}}}
and I have also class like this.
class Fixture
{
//public string results { get; set; }
public string fixture_id { get; set; }
public string event_timestamp { get; set; }
public string event_date { get; set; }
public string league_id { get; set; }
public string round { get; set; }
public string homeTeam_id { get; set; }
public string awayTeam_id { get; set; }
public string homeTeam { get; set; }
public string awayTeam { get; set; }
public string status { get; set; }
public string statusShort { get; set; }
public string goalsHomeTeam { get; set; }
public string goalsAwayTeam { get; set; }
public string halftime_score { get; set; }
public string final_score { get; set; }
public string penalty { get; set; }
public string elapsed { get; set; }
public string firstHalfStart { get; set; }
public string secondHalfStart { get; set; }
}
My code is on below
try
{
string _url = string.Format("https://api-football-v1.p.mashape.com/fixtures/date/{0}",(DateTime.Now.Year+"-"+DateTime.Now.Month+"-"+DateTime.Now.Day).ToString());
//PERFORM IN BACKGROUND
await Task.Run(async () =>
{
var fixtures= await _url.WithHeader("Accept", "application/json").WithHeader("X-Mashape-Key", "g5vnMIqeChmshvK6H25VPavNCfhHp1KUtTkjsnOqEM06eP6cOd").GetJsonAsync<Fixture>();
});
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
I try to get JSON data with Flurl.HTTP. But I have deserialized problem. Where is my mistake?
How can I parse this JSON data to IList in c#?
Thank you for your support friends...

You're basically trying to select an inner section of the JSON response, and you can't do that - you need to deserialize to a structure representing the entire response, then traverse this structure to get an individual Fixture. Looking at full response body, you will need to add 2 more classes to contain this structure:
public class ResponseBody
{
public Api api { get; set; }
}
public class Api
{
public int results { get; set; }
public Dictionary<string, Fixture> fixtures { get; set; }
}
Then call GetJsonAsync<ResponseBody>() instead of GetJsonAsync<Fixture>().

Related

Deserialize json without root object and 1 array ASP.NET MVC

I'm building a web application that's using a third parties API and I receive the json below
{
"CompanyID": 14585,
"CompanyName": "The Morgan Group Daytona, LLC",
"BillingAddressLine": "100 S Beach St #200",
"BillingAddressCity": "Daytona Beach",
"BillingAddressState": "Fl",
"BillingAddressPostCode": "32114",
"BillingCountryCode": "US",
"BillingAddress": "100 S Beach St #200\r\nDaytona Beach Fl 32114\r\nUNITED STATES",
"Phone": null,
"Fax": null,
"website": null,
"TaxNumber": null,
"Comments": null,
"CurrencyCode": "USD",
"DefaultTradingTermIDFK": 15,
"DateCreated": "2020-09-04T18:25:02",
"DateUpdated": "2020-09-04T18:25:02",
"Contacts": [
{
"ContactID": 13781,
"CompanyIDFK": 14585,
"CompanyName": null,
"Firstname": "Test",
"Lastname": "User",
"Email": "test#test.com",
"Phone": null,
"Mobile": "4075551234",
"PositionTitle": "Test Title",
"TimeZone": "Eastern Standard Time",
"DateCreated": "2020-09-07T02:21:10",
"DateUpdated": "2020-09-07T02:21:10"
}
]
}
All of the other json responses for the other API calls also do not have root objects. The goal is to use razor to display this information on the view. Whats the most efficient way to do so?
So far I've created this class file
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
but now i'm stuck on trying to figure out how to deserialize something like this? Whats the easiest way to do this. I can't seem to find any other post that matches this same set of circumstances.
When you get a blob of JSON, you can speed things up by going to https://json2csharp.com/ and have it convert it in to classes. For example, that blob returns this:
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string website { get; set; }
public string TaxNumber { get; set; }
public string Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
The classes it returns will sometimes have some small issues, for example, since your blob had a lot of null properties, it just converted them to object. I changed them to string.
Then you simply use Newtonsoft.Json to convert it:
using(var s = File.OpenRead(#"c:\users\andy\desktop\test.json"))
using(var sr = new StreamReader(s))
using(var jtr = new JsonTextReader(sr))
{
var obj = new JsonSerializer().Deserialize<Root>(jtr);
}
And you are finished:
ETA
You posted your code on getting this data and noticed you are using WebRequest. Just a heads up that WebRequest is legacy and you should be using HttpClient. This is how you download/deserialize with HttpClient:
private static readonly HttpClient _httpClient = new HttpClient();
private static async Task<Root> GetStuffFromThereAsync(string token)
{
using(var req = new HttpRequestMessage(HttpMethod.Get,
new Uri("https://www.example.com")))
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var resp = await _httpClient.SendAsync(req))
{
resp.EnsureSuccessStatusCode();
using (var s = await resp.Content.ReadAsStreamAsync())
using (var sr = new StreamReader(s))
using (var jtr = new JsonTextReader(sr))
{
return new JsonSerializer().Deserialize<Root>(jtr);
}
}
}
}
If it is still returning null, then there is a chance your models don't match.
You need to use the below the line with class I have mentioned :
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>("This is the your JSON string");
Class
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}

Error while deserilizing json in C#

I am getting response in json like this
data={"Id": "234", "Name": "pinky", "MobileNumber": "", "ClassName": "Class1_Physics", "DOBTime": "1990-04-11 15:46:38", "Landline": "", "Status": "Unmarried"}
I want to deserilize json and insert into table.
I have created 2 classes for it and using dll of Newtonsoft for deserilization.
public class JsonResult
{
public string Id { get; set; }
public string Name { get; set; }
public string MobileNumber { get; set; }
public string ClassName { get; set; }
public string DOBTime { get; set; }
public string Landline { get; set; }
public string Status { get; set; }
}
public class JsonResultRoot
{
[JsonProperty(PropertyName = "data")]
public string Data { get; set; }
public JsonResult JsonResult
{
get { return JsonConvert.DeserializeObject<JsonResult>(Data); }
}
}
Code :
decodedUrl : store actual json data/string
var JsonData = JsonConvert.DeserializeObject(decodedUrl).JsonResult;
If your JSON contains this data= part, then it is invalid JSON. You cannot deserialize it using JSON.NET library.
In order to deserialize this, you can simply clean this part out:
public class JsonResult
{
public string Id { get; set; }
public string Name { get; set; }
public string MobileNumber { get; set; }
public string ClassName { get; set; }
public string DOBTime { get; set; }
public string Landline { get; set; }
public string Status { get; set; }
}
// Usage:
jsonString = jsonString.Replace("data=").Trim();
var jsonObject = JsonConvert.DeserializeObject<JsonResult>(jsonString);
Of course, in general it looks bad. You should only do it if "you are getting response in json like this" and you can do nothing about it.
If there is any possibility to make incoming format correct, then better do it.

Parse Complex JSON to ASP.NET MVC 3 using jQuery

I have to post this javascript object to asp.net controller:
The model in server side is:
public class UserExperience
{
public class competences
{
public string id { get; set; }
public string level { get; set; }
public string name { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
public long id { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string projectName { get; set; }
public string company { get; set; }
public string customerIndustry { get; set; }
public string jobTitle { get; set; }
public string projectDescription { get; set; }
public string responsabilities { get; set; }
public List<competences> competence { get; set; }
public List<int> deletedCompetences { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
I tried to send the json like this:
$.ajax("/candidate/saveUserExperience", {
data : JSON.stringify({ue: is.Candidate.BO.userExperience[id]}),
//dataType: "text",
contentType : "application/json",
type : 'POST'
})
And this is the controller where I receive it:
public JsonResult saveUserExperience(UserExperience ue)
{
bool success;
success = true;
return Json(new { success, ue }, JsonRequestBehavior.AllowGet);
}
And I receive a null object.
I tried to do with:
UserExperience userExperience = new JavaScriptSerializer().Deserialize<UserExperience>(ue);
and I do not receive the competence subclass object.
Is there a solution to this problem ?
Thanks.
Why are you trying to pass is.Candidate.BO.userExperience[id] when you expect UserExperience object? Just write data: ue in ajax call parameters,

Json payload with a toString property

I keep getting a property set to null when I try to deserialize json which contains a toString name for a property
{
"field": "status",
"fieldtype": "jira",
"from": "10000",
"fromString": "Impeded",
"to": "10006",
"toString": "Review"
}
I tried with and without the following JsonProperty
public class ChangelogItem
{
public string field { get; set; }
public string fieldtype { get; set; }
public string from { get; set; }
public string fromString { get; set; }
public string to { get; set; }
//[JsonProperty(PropertyName = "toString")]
//public string newString { get; set; }
public string toString { get; set; }
}
but I keep getting a null value.
Any idea?
The following works fine for me with Json.Net v6.0.3:
public class ChangelogItem
{
public string field { get; set; }
public string fieldtype { get; set; }
public string from { get; set; }
public string fromString { get; set; }
public string to { get; set; }
public string toString { get; set; }
}
Test program:
class Program
{
static void Main(string[] args)
{
string json = #"
{
""field"": ""status"",
""fieldtype"": ""jira"",
""from"": ""10000"",
""fromString"": ""Impeded"",
""to"": ""10006"",
""toString"": ""Review""
}";
ChangelogItem item = JsonConvert.DeserializeObject<ChangelogItem>(json);
Console.WriteLine(item.toString);
}
}
Output:
Review

ServiceStack, OrmLite Issue Saving Related Entities

I've searched for a while looking for a solution to this problem and haven't found anything.
I'm trying to POST a Client DTO and it's related Contacts DTOs to my ServiceStack web service but I'm getting an error. I've followed along with the OrmLite tests located here.
My DTOs:
public partial class Client {
[AutoIncrement]
public int ID { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public decimal? Latitude { get; set; }
public decimal? Longitude { get; set; }
public string HomePhoneAreaCode { get; set; }
public string HomePhoneExchange { get; set; }
public string HomePhoneNumber { get; set; }
public string HomeFaxAreaCode { get; set; }
public string HomeFaxExchange { get; set; }
public string HomeFaxNumber { get; set; }
public string KeyNumber { get; set; }
public string AlarmCode { get; set; }
public string GarageDoorCode { get; set; }
public string MyAPCUsername { get; set; }
public string MyAPCPassword { get; set; }
public bool IsActive { get; set; }
public string Notes { get; set; }
[Reference]
public List<Contact> Contacts { get; set; }
}
public partial class Contact {
[AutoIncrement]
public int ID { get; set; }
public int ClientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string WorkPhoneAreaCode { get; set; }
public string WorkPhoneExchange { get; set; }
public string WorkPhoneNumber { get; set; }
public string MobilePhoneAreaCode { get; set; }
public string MobilePhoneExchange { get; set; }
public string MobilePhoneNumber { get; set; }
public bool CanSMS { get; set; }
public string PersonalEmail { get; set; }
public string WorkEmail { get; set; }
public string AlternateEmail { get; set; }
public int Ordinal { get; set; }
[Reference]
public Client Client { get; set; }
}
In my Service:
public int Post(Client client) {
Db.Save(client, references: true);
return client.ID;
}
And my test code:
var newClient = new Client {
Street = "1234 Any Avenue",
City = "Gorham",
State = "ME",
ZipCode = "22222",
HomePhoneAreaCode = "123",
HomePhoneExchange = "456",
HomePhoneNumber = "7890",
HomeFaxAreaCode = "098",
HomeFaxExchange = "765",
HomeFaxNumber = "4321",
KeyNumber = "99",
AlarmCode = "1234",
GarageDoorCode = "abcd",
IsActive = true,
Notes = "These are the notes for the new client.",
Contacts = new List<Contact>() {
new Contact { FirstName = "John", LastName = "Doe", PersonalEmail = "john.doe#gmail.com", CanSMS = true, Ordinal = 1 },
new Contact { FirstName = "Jane", LastName = "Smith", PersonalEmail = "jane.smith#gmail.com", CanSMS = false, Ordinal = 2 }
},
};
// POST entity
int newClientID = serviceClient.Post<int>(newClient);
The last line produces the error -
WebServiceException, message "Cant find 'ClientId' Property on Type 'Contact'"
I've tried different combinations of the Reference, References, and ForeignKey attributes to no avail.
Any help would be appreciated.
Thanks,
Jay

Resources