This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Closed 2 years ago.
So i am trying to get the values from this JSON file the json file
{
"Global Quote": {
"01. symbol": "IBM",
"02. open": "125.8300",
"03. high": "126.2500",
"04. low": "123.4000",
"05. price": "124.1500",
"06. volume": "3115104",
"07. latest trading day": "2020-06-17",
"08. previous close": "125.1500",
"09. change": "-1.0000",
"10. change percent": "-0.7990%"
}
}
i tried to create class with special paste in visual studio and it gave a result like this:
public class Rootobject
{
public GlobalQuote GlobalQuote { get; set; }
}
public class GlobalQuote
{
public string _01symbol { get; set; }
public string _02open { get; set; }
public string _03high { get; set; }
public string _04low { get; set; }
public string _05price { get; set; }
public string _06volume { get; set; }
public string _07latesttradingday { get; set; }
public string _08previousclose { get; set; }
public string _09change { get; set; }
public string _10changepercent { get; set; }
}
WebClient webClient = new WebClient();
string result = webClient.DownloadString("URL Source");// the result is the json file
GlobalQuote m = JsonConvert.DeserializeObject<GlobalQuote>(result);
Console.WriteLine(m._01symbol);
Console.WriteLine(m._02open);
Console.WriteLine(m._03high);
it gave me nothing. i think the problem is that the attributs in the class does not match with JSON file.
the problem that the attributs in the JSON file contains space.
So i am searching for a solution to get values from JSON file without using class. Can anyone help me please and thanks in advance.
So finally i found a solution to my problem:
public class Rootobject
{
[JsonProperty(PropertyName = "Global Quote")]
public GlobalQuote GlobalQuote { get; set; }
}
public class GlobalQuote
{
[JsonProperty(PropertyName = "01. symbol")]
public string _01symbol { get; set; }
[JsonProperty(PropertyName = "02. open")]
public string _02open { get; set; }
[JsonProperty(PropertyName = "03. high")]
public string _03high { get; set; }
[JsonProperty(PropertyName = "04. low")]
public string _04low { get; set; }
[JsonProperty(PropertyName = "05. price")]
public string _05price { get; set; }
[JsonProperty(PropertyName = "06. volume")]
public string _06volume { get; set; }
[JsonProperty(PropertyName = "07. latest trading day")]
public string _07latesttradingday { get; set; }
[JsonProperty(PropertyName = "08. previous close")]
public string _08previousclose { get; set; }
[JsonProperty(PropertyName = "09. change")]
public string _09change { get; set; }
[JsonProperty(PropertyName = "10. change percent")]
public string _10changepercent { get; set; }
}
Rootobject oRootObject = new Rootobject();
oRootObject = JsonConvert.DeserializeObject<Rootobject>(result);
Console.Writeline(oRootObject.GlobalQuote._02open);
Related
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; }
}
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>().
I need some help with custom serialization using Newtonsoft Json (Json.Net). I have classes like below:
public class Person
{
[JsonProperty(PropertyName = "PersonName")]
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
public Address PersonAddress { get; set; }
}
public class Address
{
[JsonProperty(PropertyName = "Address1")]
public string Address1 { get; set; }
[JsonIgnore]
public string Address2 { get; set; }
[JsonProperty(PropertyName = "City")]
public string City { get; set; }
[JsonProperty(PropertyName = "State")]
public string State { get; set; }
[JsonIgnore]
public string Country { get; set; }
}
When I serialize the above class it should return output like below:
{
"PersonName":"Name",
"Address1":"Address1",
"City":"City",
"State":"state"
}
How can I do it using Newtonsoft?
You can create a third class as follows:
public class Rootobject
{
public string PersonName { get; set; }
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Then, an object out of it like this:
var rootObject = new Rootobject()
{
PersonName = person.Name,
Address1 = address.Address1,
City = address.City,
State = address.State
};
And finally serialize it using JsonCovert:
var result = JsonConvert.SerializeObject(rootObject);
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
I'm having trouble with parsing a twitter flow, this code is returning this error message:
No parameterless constructor defined for type of
'System.Collections.Generic.IEnumerable`1[[Xxxx.Website.Templates.WidgetViews.Tweet,
Dolphin, Version=1.0.4801.24288, Culture=neutral,
PublicKeyToken=null]]'.
I would very much appreciate your help!
public partial class TwitterWidgetView
{
protected override void OnLoad(System.EventArgs e)
{
string listName = "sas";
string twitterListPath = "https://search.twitter.com/search.json?q=" + listName;
WebClient wc = new WebClient();
var json = wc.DownloadString(twitterListPath);
JavaScriptSerializer ser = new JavaScriptSerializer();
var tweetList = ser.Deserialize<IEnumerable<Tweet>>(json);
}
}
public class Metadata
{
public string result_type { get; set; }
}
public class Tweet
{
public Tweet()
{}
public string created_at { get; set; }
public string from_user { get; set; }
public int from_user_id { get; set; }
public string from_user_id_str { get; set; }
public string from_user_name { get; set; }
public object geo { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string iso_language_code { get; set; }
public Metadata metadata { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string source { get; set; }
public string text { get; set; }
public string to_user { get; set; }
public int to_user_id { get; set; }
public string to_user_id_str { get; set; }
public string to_user_name { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
}
public class RootObject
{
public RootObject()
{}
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_page { get; set; }
public int page { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public List<Tweet> results { get; set; }
public int results_per_page { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
Try using a list instead
var tweetList = ser.Deserialize<List<Tweet>>(json);