I'm trying to deserialize a JSON from here. And I can't use i.e. properties from class Global.
namespace CoVID2
{
public class CovidStats
{
public string ID { get; set; }
public string Message { get; set; }
public class Global {
public int NewConfirmed { get; set; }
public int TotalConfirmed { get; set; }
public int NewDeaths { get; set; }
public int TotalDeaths { get; set; }
public int NewRecovered { get; set; }
public int TotalRecovered { get; set; }
public string Date { get; set; }
}
}
private void button1_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
string s = client.DownloadString(url);
CovidStats stat = JsonConvert.DeserializeObject<CovidStats>(s);
MessageBox.Show(stat.Global.TotalConfirmed.ToString()); // This is the place, where i get an error
}
}
Error CS0572 'Global': cannot reference a type through an expression; try 'CovidStats.Global' instead CoVID2 C:\Users\Yan\source\repos\CoVID2\CoVID2\Form1.cs 64 Active
Error CS0120 An object reference is required for the non-static field, method, or property 'CovidStats.Global.TotalConfirmed' CoVID2 C:\Users\Yan\source\repos\CoVID2\CoVID2\Form1.cs 64 Active
You can use https://json2csharp.com/ to easily convert valid JSON string into C# classes.
Based on the JSON from https://api.covid19api.com/summary I got the following result:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Global
{
public int NewConfirmed { get; set; }
public int TotalConfirmed { get; set; }
public int NewDeaths { get; set; }
public int TotalDeaths { get; set; }
public int NewRecovered { get; set; }
public int TotalRecovered { get; set; }
public DateTime Date { get; set; }
}
public class Premium
{
}
public class Country
{
public string ID { get; set; }
public string Country { get; set; }
public string CountryCode { get; set; }
public string Slug { get; set; }
public int NewConfirmed { get; set; }
public int TotalConfirmed { get; set; }
public int NewDeaths { get; set; }
public int TotalDeaths { get; set; }
public int NewRecovered { get; set; }
public int TotalRecovered { get; set; }
public DateTime Date { get; set; }
public Premium Premium { get; set; }
}
public class Root
{
public string ID { get; set; }
public string Message { get; set; }
public Global Global { get; set; }
public List<Country> Countries { get; set; }
public DateTime Date { get; set; }
}
My jsonResponse is something like this:
{"status":200,"data":{"first_name":"\u062e\u0633","last_name":"\u0635\u062f\u0627","national_code":"1","image_photo":"1.jpg","cellphone":"1234","city":{"id":1,"name":"x","created_at":"2017-02-27 17:54:44","updated_at":"2017-02-27 17:54:44"},"email":"something#gmail.com","even_odd":1,"Register Time":"2018-01-25 10:39:17","is_blocked":false,"receive_regular_offer":"false","level":1,"ride_count":0,"service_type":1,"bank":"\u0645","iban":"xy","card_number":"","holder":"\u062e\u0633","plate_number":"123","vehicle_model":"\u067e\u0698","vehicle_color":"\u062a\u0627\u06a9\u0633","unique_id":592875}}
I have created a class like this:
public class Driver
{
public string first_name { get; set; }
public string last_name { get; set; }
public string national_code { get; set; }
public string image_photo { get; set; }
public string cellphone { get; set; }
public string city { get; set; }
public string email { get; set; }
public string even_odd { get; set; }
public bool is_blocked { get; set; }
public bool receive_regular_offer { get; set; }
public string level { get; set; }
public string ride_count { get; set; }
public string service_type { get; set; }
public string bank { get; set; }
public string iban { get; set; }
public string card_number { get; set; }
public string holder { get; set; }
public string vehicle_model { get; set; }
public string vehicle_color { get; set; }
public string unique_id { get; set; }
}
and used this:
jsonResponse = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
Driver snappDriver = js.Deserialize<Driver>(jsonResponse);
But the result is all null!
1.your class should be defined right
example:
void Main()
{
var json =api();
//dynamic
var dynamic_json = JsonConvert.DeserializeObject(json).Dump() as JObject;
//strong type
var strong_Type_json = JsonConvert.DeserializeObject<Driver>(json).Dump() ;
}
string api(){
return #"
{""status"":200,""data"":{""first_name"":""\u062e\u0633"",""last_name"":""\u0635\u062f\u0627"",""national_code"":""1"",""image_photo"":""1.jpg"",""cellphone"":""1234"",""city"":{""id"":1,""name"":""x"",""created_at"":""2017-02-27 17:54:44"",""updated_at"":""2017-02-27 17:54:44""},""email"":""something#gmail.com"",""even_odd"":1,""Register_Time"":""2018-01-25 10:39:17"",""is_blocked"":false,""receive_regular_offer"":""false"",""level"":1,""ride_count"":0,""service_type"":1,""bank"":""\u0645"",""iban"":""xy"",""card_number"":"""",""holder"":""\u062e\u0633"",""plate_number"":""123"",""vehicle_model"":""\u067e\u0698"",""vehicle_color"":""\u062a\u0627\u06a9\u0633"",""unique_id"":592875}}
";
}
public class City
{
public int id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
public class Data
{
public string first_name { get; set; }
public string last_name { get; set; }
public string national_code { get; set; }
public string image_photo { get; set; }
public string cellphone { get; set; }
public City city { get; set; }
public string email { get; set; }
public int even_odd { get; set; }
public string Register_Time { get; set; }
public bool is_blocked { get; set; }
public string receive_regular_offer { get; set; }
public int level { get; set; }
public int ride_count { get; set; }
public int service_type { get; set; }
public string bank { get; set; }
public string iban { get; set; }
public string card_number { get; set; }
public string holder { get; set; }
public string plate_number { get; set; }
public string vehicle_model { get; set; }
public string vehicle_color { get; set; }
public int unique_id { get; set; }
}
public class Driver
{
public int status { get; set; }
public Data data { get; set; }
}
2.json's key Register Time in strong type is invalid name
you can add _ in your json string to solve the problem
Try to create exactly the same class definition as your json has. Your Driver class describes json object's data property.
public class DriverWrapper
{
public string status { get; set; }
public Driver data { get; set; }
}
You have to create another object class that handles status and data property
try this
Create a class Response
class Response{
public int status { get; set;}
public Driver data { get; set;}
}
and do it this way
jsonResponse = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
Response snappDriver = js.Deserialize<Response>(jsonResponse);
I'm trying to use Integration Studio for the first time to create an extension to make an API call with a file upload. Unfortunately, I'm not very well versed with .NET. This is the code I'm trying to replicate on Integration Studio:
public static async Task<PendingAttachment> Upload(string FilePath)
{
byte[] byteFile = System.IO.File.ReadAllBytes(FilePath);
FileInfo fi = new FileInfo(FilePath);
PendingAttachment pa = null;
using (var client = new HttpClient())
{
string token = "XXXXXXXXXXXXX";
client.DefaultRequestHeaders.Add("Authorization", "Bearer" + token);
using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
content.Add(new StreamContent(new MemoryStream(byteFile)), "attachment", fi.Name);
using (var message = await client.PostAsync("https://www.yammer.com/api/v1/pending_attachments", content))
{
if (message.IsSuccessStatusCode)
{
var result = await message.Content.ReadAsStringAsync();
pa = Newtonsoft.Json.JsonConvert.DeserializeObject<PendingAttachment>(result);
return pa;
}
}
}
}
return null;
}
So, this is what I've tried. I have created the following structures on Integration Studio:
public class PendingAttachment
{
public int id { get; set; }
public int network_id { get; set; }
public string url { get; set; }
public string web_url { get; set; }
public string type { get; set; }
public string name { get; set; }
public string original_name { get; set; }
public string full_name { get; set; }
public string description { get; set; }
public string content_type { get; set; }
public string content_class { get; set; }
public string created_at { get; set; }
public int owner_id { get; set; }
public bool official { get; set; }
public string small_icon_url { get; set; }
public string large_icon_url { get; set; }
public string download_url { get; set; }
public string thumbnail_url { get; set; }
public string preview_url { get; set; }
public string large_preview_url { get; set; }
public int size { get; set; }
public string owner_type { get; set; }
public string last_uploaded_at { get; set; }
public int last_uploaded_by_id { get; set; }
public string last_uploaded_by_type { get; set; }
public object uuid { get; set; }
public object transcoded { get; set; }
public object streaming_url { get; set; }
public string path { get; set; }
public int y_id { get; set; }
public string overlay_url { get; set; }
public string privacy { get; set; }
public object group_id { get; set; }
public bool is_pending { get; set; }
public int height { get; set; }
public int width { get; set; }
public string scaled_url { get; set; }
public Image image { get; set; }
public int latest_version_id { get; set; }
public string status { get; set; }
public Latest_Version latest_version { get; set; }
public Stats stats { get; set; }
public string _OriginalFileName { get; set; }
}
public class Image
{
public string url { get; set; }
public int size { get; set; }
public string thumbnail_url { get; set; }
}
public class Latest_Version
{
public int id { get; set; }
public int file_id { get; set; }
public string content_type { get; set; }
public int size { get; set; }
public int uploader_id { get; set; }
public string created_at { get; set; }
public string path { get; set; }
public string download_url { get; set; }
public string thumbnail_url { get; set; }
public string preview_url { get; set; }
public string large_preview_url { get; set; }
public string post_processed_id { get; set; }
public object streaming_url { get; set; }
public string revert_url { get; set; }
public int height { get; set; }
public int width { get; set; }
public string scaled_url { get; set; }
public string thumbnail_path { get; set; }
public string preview_path { get; set; }
public string large_preview_path { get; set; }
public string status { get; set; }
}
public class Stats
{
public int following { get; set; }
public int followers { get; set; }
public int updates { get; set; }
public object first_reply_id { get; set; }
public object first_reply_at { get; set; }
public int latest_reply_id { get; set; }
public string latest_reply_at { get; set; }
public int shares { get; set; }
}
As this extension will be used for mobile, I have added 2 input parameters, to send the FileData as well as the FileName, to avoid having to extract that data. I have added an output parameter with the data type PendingAttachment which is the structure mentioned above.
So the issue I'm facing is that since it is an async method, Visual Studio isn't allowing me to have an output parameter. So is there a way to fix this?
P.S: Yes, I have tried implementing this normally on Service Studio, by referencing the Box File Upload plugin. It did not work (gave a 500 error). I have also been assured that this method works properly.
Thank you for your help!
If you need to use an async method in one that's not, you can call the method .Wait() on the Task object returned by the async method. This will hold the calling thread until the asynchronous code has been fully executed.
I deserialize complex JSON (Spotify Playlist) and get root level values but I cannot get branches values. I Google problem, try different options without success but, I assume its silly mistake or lack of knowledge so therefore just ask for help what I am missing?
My classes are:
public class Playlist
{
public string collaborative { get; set; }
public string description { get; set; }
//public <ExternalUrls> external_urls { get; set; } //object
//public List<Followers> followers { get; set; } //object
public string href { get; set; }
public string id { get; set; }
//public List<Image> images { get; set; } //array
public string name { get; set; }
}
public class Tracks
{
public string href { get; set; }
public Item items { get; set; } //object
public string limit { get; set; }
public string next { get; set; }
public string offset { get; set; }
public string previous { get; set; }
public string total { get; set; }
}
And code to deserialize looks like that:
StreamReader responseFromServer = new StreamReader(myWebResponse.GetResponseStream());
var dataResponse = responseFromServer.ReadToEnd();
responseFromServer.Close();
var elements = new JavaScriptSerializer().Deserialize<Playlist>(dataResponse);
RootBuffer.AddRow();
RootBuffer.collaborative = elements.collaborative.ToString();
foreach (Tracks trs in elements.tracks)
{
TracksBuffer.AddRow();
TracksBuffer.href = trs.href.ToString()
}
I genereated the classes using this excellent site: json2csharp.com
And used your existing deserialization code successfully with the following classes. It populated all the data including the child collections (brace yourself, it's a long one):
public class Playlist
{
public bool collaborative { get; set; }
public string description { get; set; }
public ExternalUrls external_urls { get; set; }
public Followers followers { get; set; }
public string href { get; set; }
public string id { get; set; }
public List<Image> images { get; set; }
public string name { get; set; }
public Owner owner { get; set; }
public bool #public { get; set; }
public string snapshot_id { get; set; }
public Tracks tracks { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls
{
public string spotify { get; set; }
}
public class Followers
{
public object href { get; set; }
public int total { get; set; }
}
public class Image
{
public object height { get; set; }
public string url { get; set; }
public object width { get; set; }
}
public class ExternalUrls2
{
public string spotify { get; set; }
}
public class Owner
{
public ExternalUrls2 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls3
{
public string spotify { get; set; }
}
public class AddedBy
{
public ExternalUrls3 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls4
{
public string spotify { get; set; }
}
public class Image2
{
public int height { get; set; }
public string url { get; set; }
public int width { get; set; }
}
public class Album
{
public string album_type { get; set; }
public List<object> available_markets { get; set; }
public ExternalUrls4 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public List<Image2> images { get; set; }
public string name { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls5
{
public string spotify { get; set; }
}
public class Artist
{
public ExternalUrls5 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalIds
{
public string isrc { get; set; }
}
public class ExternalUrls6
{
public string spotify { get; set; }
}
public class Track
{
public Album album { get; set; }
public List<Artist> artists { get; set; }
public List<object> available_markets { get; set; }
public int disc_number { get; set; }
public int duration_ms { get; set; }
public bool #explicit { get; set; }
public ExternalIds external_ids { get; set; }
public ExternalUrls6 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string name { get; set; }
public int popularity { get; set; }
public string preview_url { get; set; }
public int track_number { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class Item
{
public string added_at { get; set; }
public AddedBy added_by { get; set; }
public bool is_local { get; set; }
public Track track { get; set; }
}
public class Tracks
{
public string href { get; set; }
public List<Item> items { get; set; }
public int limit { get; set; }
public object next { get; set; }
public int offset { get; set; }
public object previous { get; set; }
public int total { get; set; }
}
Hope this helps.
I am using the following tutorial to parse a JSON document.
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
The JSON document that I am trying to parse can be accessed here:
http://www.visitproject.co.uk/Tweets/Ireland.txt
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic tweets = jss.Deserialize(json, typeof(object)) as dynamic;
foreach (var tweettext in tweets.statuses.text)
{
Console.WriteLine("Tweet: " + tweettext);
}
I am able to perform a watch on tweets.statuses and it does contain a collection of tweets. I would like to get the text value from each tweet. The only thing I can see that is different for the tutorial is that it is an array in JSON and I expect that this is why it is not working. Does anyone have any ideas? Thank you for your help!
You could use LINQ to JSON, like this:
// Parse JSON
JObject o = JObject.Parse(json);
Read LINQ to JSON documentation for details on how to query for the pieces of JSON you want.
You can simply copy paste the code below and get your answer.
This is how i parsed your json data.
I created classes based on your json
public class Metadata
{
public string result_type { get; set; }
public string iso_language_code { get; set; }
}
public class Url2
{
public string url { get; set; }
public string expanded_url { get; set; }
public string display_url { get; set; }
public List<int> indices { get; set; }
}
public class Url
{
public List<Url2> urls { get; set; }
}
public class Description
{
public List<object> urls { get; set; }
}
public class Entities
{
public Url url { get; set; }
public Description description { get; set; }
}
public class User
{
public int id { get; set; }
public string id_str { get; set; }
public string name { get; set; }
public string screen_name { get; set; }
public string location { get; set; }
public string description { get; set; }
public string url { get; set; }
public Entities entities { get; set; }
public bool #protected { get; set; }
public int followers_count { get; set; }
public int friends_count { get; set; }
public int listed_count { get; set; }
public string created_at { get; set; }
public int favourites_count { get; set; }
public int? utc_offset { get; set; }
public string time_zone { get; set; }
public bool geo_enabled { get; set; }
public bool verified { get; set; }
public int statuses_count { get; set; }
public string lang { get; set; }
public bool contributors_enabled { get; set; }
public bool is_translator { get; set; }
public string profile_background_color { get; set; }
public string profile_background_image_url { get; set; }
public string profile_background_image_url_https { get; set; }
public bool profile_background_tile { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string profile_link_color { get; set; }
public string profile_sidebar_border_color { get; set; }
public string profile_sidebar_fill_color { get; set; }
public string profile_text_color { get; set; }
public bool profile_use_background_image { get; set; }
public bool default_profile { get; set; }
public bool default_profile_image { get; set; }
public bool following { get; set; }
public bool follow_request_sent { get; set; }
public bool notifications { get; set; }
public string profile_banner_url { get; set; }
}
public class Large
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Medium2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Thumb
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Small
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Sizes
{
public Large large { get; set; }
public Medium2 medium { get; set; }
public Thumb thumb { get; set; }
public Small small { get; set; }
}
public class Medium
{
public object id { get; set; }
public string id_str { get; set; }
public List<int> indices { get; set; }
public string media_url { get; set; }
public string media_url_https { get; set; }
public string url { get; set; }
public string display_url { get; set; }
public string expanded_url { get; set; }
public string type { get; set; }
public Sizes sizes { get; set; }
public long source_status_id { get; set; }
public string source_status_id_str { get; set; }
}
public class Entities2
{
public List<object> hashtags { get; set; }
public List<object> symbols { get; set; }
public List<object> urls { get; set; }
public List<object> user_mentions { get; set; }
public List<Medium> media { get; set; }
}
public class Metadata2
{
public string result_type { get; set; }
public string iso_language_code { get; set; }
}
public class Description2
{
public List<object> urls { get; set; }
}
public class Url4
{
public string url { get; set; }
public string expanded_url { get; set; }
public string display_url { get; set; }
public List<int> indices { get; set; }
}
public class Url3
{
public List<Url4> urls { get; set; }
}
public class Entities3
{
public Description2 description { get; set; }
public Url3 url { get; set; }
}
public class User2
{
public int id { get; set; }
public string id_str { get; set; }
public string name { get; set; }
public string screen_name { get; set; }
public string location { get; set; }
public string description { get; set; }
public string url { get; set; }
public Entities3 entities { get; set; }
public bool #protected { get; set; }
public int followers_count { get; set; }
public int friends_count { get; set; }
public int listed_count { get; set; }
public string created_at { get; set; }
public int favourites_count { get; set; }
public int utc_offset { get; set; }
public string time_zone { get; set; }
public bool geo_enabled { get; set; }
public bool verified { get; set; }
public int statuses_count { get; set; }
public string lang { get; set; }
public bool contributors_enabled { get; set; }
public bool is_translator { get; set; }
public string profile_background_color { get; set; }
public string profile_background_image_url { get; set; }
public string profile_background_image_url_https { get; set; }
public bool profile_background_tile { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string profile_banner_url { get; set; }
public string profile_link_color { get; set; }
public string profile_sidebar_border_color { get; set; }
public string profile_sidebar_fill_color { get; set; }
public string profile_text_color { get; set; }
public bool profile_use_background_image { get; set; }
public bool default_profile { get; set; }
public bool default_profile_image { get; set; }
public bool following { get; set; }
public bool follow_request_sent { get; set; }
public bool notifications { get; set; }
}
public class Medium4
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Large2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Thumb2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Small2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Sizes2
{
public Medium4 medium { get; set; }
public Large2 large { get; set; }
public Thumb2 thumb { get; set; }
public Small2 small { get; set; }
}
public class Medium3
{
public long id { get; set; }
public string id_str { get; set; }
public List<int> indices { get; set; }
public string media_url { get; set; }
public string media_url_https { get; set; }
public string url { get; set; }
public string display_url { get; set; }
public string expanded_url { get; set; }
public string type { get; set; }
public Sizes2 sizes { get; set; }
}
public class Entities4
{
public List<object> hashtags { get; set; }
public List<object> symbols { get; set; }
public List<object> urls { get; set; }
public List<object> user_mentions { get; set; }
public List<Medium3> media { get; set; }
}
public class RetweetedStatus
{
public Metadata2 metadata { get; set; }
public string created_at { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string text { get; set; }
public string source { get; set; }
public bool truncated { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
public int? in_reply_to_user_id { get; set; }
public string in_reply_to_user_id_str { get; set; }
public string in_reply_to_screen_name { get; set; }
public User2 user { get; set; }
public object geo { get; set; }
public object coordinates { get; set; }
public object place { get; set; }
public object contributors { get; set; }
public int retweet_count { get; set; }
public int favorite_count { get; set; }
public Entities4 entities { get; set; }
public bool favorited { get; set; }
public bool retweeted { get; set; }
public bool possibly_sensitive { get; set; }
public string lang { get; set; }
}
public class Status
{
public Metadata metadata { get; set; }
public string created_at { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string text { get; set; }
public string source { get; set; }
public bool truncated { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
public int? in_reply_to_user_id { get; set; }
public string in_reply_to_user_id_str { get; set; }
public string in_reply_to_screen_name { get; set; }
public User user { get; set; }
public object geo { get; set; }
public object coordinates { get; set; }
public object place { get; set; }
public object contributors { get; set; }
public int retweet_count { get; set; }
public int favorite_count { get; set; }
public Entities2 entities { get; set; }
public bool favorited { get; set; }
public bool retweeted { get; set; }
public bool possibly_sensitive { get; set; }
public string lang { get; set; }
public RetweetedStatus retweeted_status { get; set; }
}
public class SearchMetadata
{
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_results { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public int count { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
public class RootObject
{
public List<Status> statuses { get; set; }
public SearchMetadata search_metadata { get; set; }
}
And i parsed your data by using the following method
public void PARSEVALUES(string jsonValue)//jsonValue contains your json
{
JavaScriptSerializer jss = new JavaScriptSerializer();
RootObject r = jss.Deserialize<RootObject>(jsonValue);
foreach (var tweetText in r.statuses)
{
string val = tweetText.text;
}
}