XML Deserializing with Lists - c#

I am using webclient to deserialize XML content from a webservice:
var serializer = new XmlSerializer(typeof(SearchArticles), new XmlRootAttribute("search_articles"));
var results = (SearchArticles)serializer.Deserialize(response.Content.ReadAsStreamAsync().Result);
The xml content is like:
<?xml version=\"1.0\" encoding=\"UTF-8\"?><search_articles><articles hits=\"10134\"><article><id>1763794</id>...
My Models look like:
public class SearchArticles
{
[XmlElement("articles")]
public ArticleHelper articles { get; set; }
}
public class ArticleHelper
{
[XmlAttribute("hits")]
public long hits { get; set; }
[XmlElement("article")]
public List<Article> articles { get; set; }
}
public class Article
{
public long id { get; set; }
public string partner { get; set; }
public string number { get; set; }
public long number_is_generated { get; set; }
public string status { get; set; }
public long company_id { get; set; }
}
This is working, but how can I avoid having the ArticleHelper ?

You can remove ArticleHelper by modifying SearchArticles and Article as:
public class SearchArticles
{
[XmlArray("articles")]
[XmlArrayItem("article", Type = typeof(Article))]
public List<Article> articles { get; set; }
}
public class Article
{
public long id { get; set; }
public string partner { get; set; }
public string number { get; set; }
public long number_is_generated { get; set; }
public string status { get; set; }
public long company_id { get; set; }
}
However, you lose access the hits attribute value.

Related

C# Getting individual data from JSON text downloaded from a site

I've been searching around for a long while for this, I haven't found any solutions to my issue which is:
I've been trying get a json data individually from a whole source seen here:
{"TargetId":0,"ProductType":null,"AssetId":1239281845,"ProductId":0,"Name":"❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack","Description":"Shirt Image","AssetTypeId":1,"Creator":{"Id":124026176,"Name":"TheDestroyerPeter","CreatorType":"User","CreatorTargetId":124026176},"IconImageAssetId":0,"Created":"2017-12-12T19:48:24.693Z","Updated":"2017-12-12T19:48:24.693Z","PriceInRobux":null,"PriceInTickets":null,"Sales":0,"IsNew":false,"IsForSale":false,"IsPublicDomain":false,"IsLimited":false,"IsLimitedUnique":false,"Remaining":null,"MinimumMembershipLevel":0,"ContentRatingTypeId":0}
now what I've been trying to do with it is get the Product Name using C# and the product name is "❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack", my issue is that I haven't found a way to extract the data, and when I have I haven't been able to get the right data, because instead if gives me "TheDestroyerPeter"
I've written up code, and deleted it, it was really sloppy and it would take awhile to rewrite, I appreciate any solutions
-whoever I am
You can use JavaScriptSerializer class, which is part of the System.Web.Script namespace.
For example :
var jsonString = #"{""name"":""John Doe"",""age"":20}";
var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonString );
and then JSONObj["name"]; gives you "John Doe"
in this case you can use it :
public class Creator
{
public int Id { get; set; }
public string Name { get; set; }
public string CreatorType { get; set; }
public int CreatorTargetId { get; set; }
}
public class RootObject
{
public int TargetId { get; set; }
public object ProductType { get; set; }
public int AssetId { get; set; }
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int AssetTypeId { get; set; }
public Creator Creator { get; set; }
public int IconImageAssetId { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public object PriceInRobux { get; set; }
public object PriceInTickets { get; set; }
public int Sales { get; set; }
public bool IsNew { get; set; }
public bool IsForSale { get; set; }
public bool IsPublicDomain { get; set; }
public bool IsLimited { get; set; }
public bool IsLimitedUnique { get; set; }
public object Remaining { get; set; }
public int MinimumMembershipLevel { get; set; }
public int ContentRatingTypeId { get; set; }
}
use Newtonsoft.Json
var jsonString = #"{""TargetId"":0,""ProductType"":null,""AssetId"":1239281845,""ProductId"":0,""Name"":""❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack"",""Description"":""Shirt Image"",""AssetTypeId"":1,""Creator"":{""Id"":124026176,""Name"":""TheDestroyerPeter"",""CreatorType"":""User"",""CreatorTargetId"":124026176},""IconImageAssetId"":0,""Created"":""2017-12-12T19:48:24.693Z"",""Updated"":""2017-12-12T19:48:24.693Z"",""PriceInRobux"":null,""PriceInTickets"":null,""Sales"":0,""IsNew"":false,""IsForSale"":false,""IsPublicDomain"":false,""IsLimited"":false,""IsLimitedUnique"":false,""Remaining"":null,""MinimumMembershipLevel"":0,""ContentRatingTypeId"":0}";
var obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine(obj.Creator.Name); //"TheDestroyerPeter"

Obtaining YouTube Statistics Using JSON (UWP, C#)

been a while since I posted here. I'm working on an app and need to fetch statistics for a particular video using JSON (C#, UWP).
I already have the statistics as a JSON string but can't seem to parse them properly using Newtonsoft. The value always comes back null. This is my code:
var url = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + cl.googleAPIKey + "&part=snippet,contentDetails,statistics,status";
var http = new HttpClient();
var response = await http.GetStringAsync(url);
var statistics = JsonConvert.DeserializeObject<Statistics>(response);
string totalViews = statistics.viewCount;
The classes generated by Json2CSharp are:
public class PageInfo
{
public int totalResults { get; set; }
public int resultsPerPage { get; set; }
}
public class Default
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Medium
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class High
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Standard
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Maxres
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Thumbnails
{
public Default #default { get; set; }
public Medium medium { get; set; }
public High high { get; set; }
public Standard standard { get; set; }
public Maxres maxres { get; set; }
}
public class Localized
{
public string title { get; set; }
public string description { get; set; }
}
public class Snippet
{
public DateTime publishedAt { get; set; }
public string channelId { get; set; }
public string title { get; set; }
public string description { get; set; }
public Thumbnails thumbnails { get; set; }
public string channelTitle { get; set; }
public List<string> tags { get; set; }
public string categoryId { get; set; }
public string liveBroadcastContent { get; set; }
public Localized localized { get; set; }
}
public class ContentDetails
{
public string duration { get; set; }
public string dimension { get; set; }
public string definition { get; set; }
public string caption { get; set; }
public bool licensedContent { get; set; }
public string projection { get; set; }
}
public class Status
{
public string uploadStatus { get; set; }
public string privacyStatus { get; set; }
public string license { get; set; }
public bool embeddable { get; set; }
public bool publicStatsViewable { get; set; }
}
public class Statistics
{
public string viewCount { get; set; }
public string likeCount { get; set; }
public string dislikeCount { get; set; }
public string favoriteCount { get; set; }
public string commentCount { get; set; }
}
public class Item
{
public string kind { get; set; }
public string etag { get; set; }
public string id { get; set; }
public Snippet snippet { get; set; }
public ContentDetails contentDetails { get; set; }
public Status status { get; set; }
public Statistics statistics { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public string etag { get; set; }
public PageInfo pageInfo { get; set; }
public List<Item> items { get; set; }
}
As I say the value will always come back as null regardless of the video ID.
Does anyone have any ideas?
Thanks
You are deserializing to the wrong class. Json2Csharp generated many classes, but Statistics is way down the tree. You should deserialize the RootObject instead:
var root = JsonConvert.DeserializeObject<RootObject>( response );
And then navigate to the statistics within the resulting class structure like for example:
foreach ( var statistics in root.Items.Select( i => i.Statistics) )
{
//do something
}

Noob C# Class Declaration Issue

So I created a class using json2csharp
public class ResponseType
{
public class Query
{
public string q { get; set; }
public object sku { get; set; }
public int limit { get; set; }
public object reference { get; set; }
public object mpn_or_sku { get; set; }
public string mpn { get; set; }
public object brand { get; set; }
public string __class__ { get; set; }
public int start { get; set; }
public object seller { get; set; }
}
public class Request
{
public bool exact_only { get; set; }
public string __class__ { get; set; }
public List<Query> queries { get; set; }
}
public class Seller
{
public string display_flag { get; set; }
public bool has_ecommerce { get; set; }
public string name { get; set; }
public string __class__ { get; set; }
public string homepage_url { get; set; }
public string id { get; set; }
public string uid { get; set; }
}
public class Prices
{
public List<List<object>> USD { get; set; }
public List<List<object>> JPY { get; set; }
public List<List<object>> CNY { get; set; }
}
public class Offer
{
public string sku { get; set; }
public string packaging { get; set; }
public string on_order_eta { get; set; }
public string last_updated { get; set; }
public int? order_multiple { get; set; }
public int in_stock_quantity { get; set; }
public string eligible_region { get; set; }
public int? moq { get; set; }
public int? on_order_quantity { get; set; }
public object octopart_rfq_url { get; set; }
public string __class__ { get; set; }
public Seller seller { get; set; }
public string product_url { get; set; }
public object factory_order_multiple { get; set; }
public string _naive_id { get; set; }
public int? factory_lead_days { get; set; }
public Prices prices { get; set; }
public bool is_authorized { get; set; }
public bool is_realtime { get; set; }
}
public class Brand
{
public string homepage_url { get; set; }
public string __class__ { get; set; }
public string name { get; set; }
public string uid { get; set; }
}
public class Manufacturer
{
public string homepage_url { get; set; }
public string __class__ { get; set; }
public string name { get; set; }
public string uid { get; set; }
}
public class Item
{
public List<Offer> offers { get; set; }
public string uid { get; set; }
public string mpn { get; set; }
public List<object> redirected_uids { get; set; }
public Brand brand { get; set; }
public string octopart_url { get; set; }
public string __class__ { get; set; }
public Manufacturer manufacturer { get; set; }
}
public class Result
{
public List<Item> items { get; set; }
public int hits { get; set; }
public string __class__ { get; set; }
public object reference { get; set; }
public object error { get; set; }
}
public class RootObject
{
public int msec { get; set; }
public Request request { get; set; }
public string __class__ { get; set; }
public List<Result> results { get; set; }
}
}
The problem is at design-time, when I declare a variable with the type of my class:
ResponseType Response = new ResponseType();
Intellisense does not allow me to access the subclasses RootObject.results list. It only shows Equals, GetHashCode, GetType and ToString. I am assuming I did something wrong in my class declaration.
Thank you in advance!
Edit -- I am fairly new to C Sharp. I am trying to parse a response from a REST API. I took the JSON provided by the Rest API and converted it using json2csharp into a class. My intent was to do something like this
Within a function return:
public ResponseType ExecuteSearch(String PartNumber)
{
~ ALL CODE FOR GENERATING req
// Perform the search and obtain results
var data = client.Execute(req).Content;
JSON = data;
return JsonConvert.DeserializeObject<ResponseType>(data);
}
Then being able to access the response as an object outside of the function
Edit 2:
I figured out what I did. Instead of nesting everything within the ResponseType I should have simply renamed RootObject to ResponseType.
Intellisense does not allow me to access the subclasses RootObject.results list
it is because the property results is not static and you try to acces it this way. A static property is accessed via ClassName.PropertyName. For more information on static variables check the link.
It only shows Equals, GetHashCode, GetType and ToString
This is the basic set of methods that every object in C# inherits from the class object. This is why you can see it.
Intellisense will allow you to do this:
ResponseType.RootObject ro = new ResponseType.RootObject();
ro.results.First();
because you will need an Instance of that class to acces the property results.
I am assuming I did something wrong in my class declaration.
It depends. Basically if the compiler does not complain then you declared your classes as supposed to be. But the declaration of the properties commands you to access them in a specific way. So if you still want to access results with RootObject.results you need to make it static:
public class RootObject
{
public static List<Result> results { get; set; }
}
But note that this list will exist only once! and is not individual to each instance of RootObject! Since you have embedded classes you need to call it like this:
ResponseType.RootObject.results.WhatEver();
EDIT
I guess you would like to get the Object of type RootObject inside the Object of type ResponseType. If I am right then it is not necessary to declare the classes inside ResponseType but you have to declare variables of each type inside it like:
public class ResponseType
{
public RootObject MyRootObject{ get; set; }
}
public class RootObject
{
public int msec { get; set; }
public Request request { get; set; }
public string __class__ { get; set; }
public List<Result> results { get; set; }
}
Now you will be able to access the results variable inside the ResponseType object:
ResponseType rt = new ResponseType();
rt.MyRootObject.results.WhatEver();
For more information on how to deserialize JSON to classes please read the Deserialize JSON to C# Classes post
1) Object with ResponseType class isn't contain any fields(event static one).
2) You declare ResponseType object, but results is field of RootObject object.
So if you want to work with results you should do something like this:
ResponseType.RootObject rootObject = new ResponseType.RootObject();
rootObject.results.DoWork();
Below is what I think you are trying to do. I would only use it in this form if this is some kind of Data Transfer Object (DTO) because otherwise it is pretty bad practice for a class that would be used in code (mostly because of the public getters and setters on all of the fields and the field names matching the class name), but it does show your main mistake and that is that classes need to be defined outside of your main class and if you need that type of class in your top level class you need to define a public field to access it.
public class ResponseType
{
public Query Query { get; set; }
public Request Request { get; set; }
public Seller Seller { get; set; }
public Prices Prices { get; set; }
public Offer Offer { get; set; }
public Brand Brand { get; set; }
public Manufacturer Manufacturer { get; set; }
public Item Item { get; set; }
public Result Result { get; set; }
public RootObject RootObject { get; set; }
}
public class Query
{
public string q { get; set; }
public object sku { get; set; }
public int limit { get; set; }
public object reference { get; set; }
public object mpn_or_sku { get; set; }
public string mpn { get; set; }
public object brand { get; set; }
public string __class__ { get; set; }
public int start { get; set; }
public object seller { get; set; }
}
public class Request
{
public bool exact_only { get; set; }
public string __class__ { get; set; }
public List<Query> queries { get; set; }
}
public class Seller
{
public string display_flag { get; set; }
public bool has_ecommerce { get; set; }
public string name { get; set; }
public string __class__ { get; set; }
public string homepage_url { get; set; }
public string id { get; set; }
public string uid { get; set; }
}
public class Prices
{
public List<List<object>> USD { get; set; }
public List<List<object>> JPY { get; set; }
public List<List<object>> CNY { get; set; }
}
public class Offer
{
public string sku { get; set; }
public string packaging { get; set; }
public string on_order_eta { get; set; }
public string last_updated { get; set; }
public int? order_multiple { get; set; }
public int in_stock_quantity { get; set; }
public string eligible_region { get; set; }
public int? moq { get; set; }
public int? on_order_quantity { get; set; }
public object octopart_rfq_url { get; set; }
public string __class__ { get; set; }
public Seller seller { get; set; }
public string product_url { get; set; }
public object factory_order_multiple { get; set; }
public string _naive_id { get; set; }
public int? factory_lead_days { get; set; }
public Prices prices { get; set; }
public bool is_authorized { get; set; }
public bool is_realtime { get; set; }
}
public class Brand
{
public string homepage_url { get; set; }
public string __class__ { get; set; }
public string name { get; set; }
public string uid { get; set; }
}
public class Manufacturer
{
public string homepage_url { get; set; }
public string __class__ { get; set; }
public string name { get; set; }
public string uid { get; set; }
}
public class Item
{
public List<Offer> offers { get; set; }
public string uid { get; set; }
public string mpn { get; set; }
public List<object> redirected_uids { get; set; }
public Brand brand { get; set; }
public string octopart_url { get; set; }
public string __class__ { get; set; }
public Manufacturer manufacturer { get; set; }
}
public class Result
{
public List<Item> items { get; set; }
public int hits { get; set; }
public string __class__ { get; set; }
public object reference { get; set; }
public object error { get; set; }
}
public class RootObject
{
public int msec { get; set; }
public Request request { get; set; }
public string __class__ { get; set; }
public List<Result> results { get; set; }
}

Not getting object data from Json deserialization

I am getting Json data from a web server, but when I try to deserialize it to objects, I am not getting any data. The Json string looks like this:
{"success":true,"data":[{"Id":6,"CustomerGuid":"70b390d8-82d5-4bba-aa68-fc8268a1b1ff","UserName":"victoria_victoria#nopCommerce.com","Email":"victoria_victoria#nopCommerce.com","CustomerRoles":[{"Id":3,"Name":"Registered","SystemName":"Registered"}],"AdminComment":null,"IsTaxExempt":false,"AffiliateId":0,"VendorId":0,"HasShoppingCartItems":false,"Active":false,"Deleted":false,"IsSystemAccount":false,"SystemName":null,"LastIpAddress":null,"CreatedOnUtc":"\/Date(1472933472393)\/","LastLoginDateUtc":null,"LastActivityDateUtc":"\/Date(1472933472393)\/","ExternalAuthenticationRecords":[],"ShoppingCartItems":[]},{"Id":5,"CustomerGuid":"eb9e6f24-f362-4c10-942a-366e2919dc11","UserName":"brenda_lindgren#nopCommerce.com","Email":"brenda_lindgren#nopCommerce.com","CustomerRoles":[{"Id":3,"Name":"Registered","SystemName":"Registered"}],"AdminComment":null,"IsTaxExempt":false,"AffiliateId":0,"VendorId":0,"HasShoppingCartItems":false,"Active":false,"Deleted":false,"IsSystemAccount":false,"SystemName":null,"LastIpAddress":null,"CreatedOnUtc":"\/Date(1472933472363)\/","LastLoginDateUtc":null,"LastActivityDateUtc":"\/Date(1472933472363)\/","ExternalAuthenticationRecords":[],"ShoppingCartItems":[]},{"Id":4,"CustomerGuid":"9f46dbae-6942-410c-90b8-9b38a0890064","UserName":"james_pan#nopCommerce.com","Email":"james_pan#nopCommerce.com","CustomerRoles":[{"Id":3,"Name":"Registered","SystemName":"Registered"}],"AdminComment":null,"IsTaxExempt":false,"AffiliateId":0,"VendorId":0,"HasShoppingCartItems":false,"Active":false,"Deleted":false,"IsSystemAccount":false,"SystemName":null,"LastIpAddress":null,"CreatedOnUtc":"\/Date(1472933472317)\/","LastLoginDateUtc":null,"LastActivityDateUtc":"\/Date(1472933472317)\/","ExternalAuthenticationRecords":[],"ShoppingCartItems":[]},{"Id":3,"CustomerGuid":"6277386b-13ee-427b-9cfe-4ebfa487c340","UserName":"arthur_holmes#nopCommerce.com","Email":"arthur_holmes#nopCommerce.com","CustomerRoles":[{"Id":3,"Name":"Registered","SystemName":"Registered"}],"AdminComment":null,"IsTaxExempt":false,"AffiliateId":0,"VendorId":0,"HasShoppingCartItems":false,"Active":false,"Deleted":false,"IsSystemAccount":false,"SystemName":null,"LastIpAddress":null,"CreatedOnUtc":"\/Date(1472933472253)\/","LastLoginDateUtc":null,"LastActivityDateUtc":"\/Date(1472933472253)\/","ExternalAuthenticationRecords":[],"ShoppingCartItems":[]},{"Id":2,"CustomerGuid":"241f45f1-b38c-4e22-8c5a-743fa3276620","UserName":"steve_gates#nopCommerce.com","Email":"steve_gates#nopCommerce.com","CustomerRoles":[{"Id":3,"Name":"Registered","SystemName":"Registered"}],"AdminComment":null,"IsTaxExempt":false,"AffiliateId":0,"VendorId":0,"HasShoppingCartItems":false,"Active":false,"Deleted":false,"IsSystemAccount":false,"SystemName":null,"LastIpAddress":null,"CreatedOnUtc":"\/Date(1472933472207)\/","LastLoginDateUtc":null,"LastActivityDateUtc":"\/Date(1472933472207)\/","ExternalAuthenticationRecords":[],"ShoppingCartItems":[]},{"Id":1,"CustomerGuid":"a940dc03-5f52-47d2-9391-8597b3b31cf2","UserName":"tony#lakesideos.com","Email":"tony#lakesideos.com","CustomerRoles":[{"Id":1,"Name":"Administrators","SystemName":"Administrators"},{"Id":2,"Name":"Forum Moderators","SystemName":"ForumModerators"},{"Id":3,"Name":"Registered","SystemName":"Registered"}],"AdminComment":null,"IsTaxExempt":false,"AffiliateId":0,"VendorId":0,"HasShoppingCartItems":true,"Active":true,"Deleted":false,"IsSystemAccount":false,"SystemName":null,"LastIpAddress":"71.185.255.7","CreatedOnUtc":"\/Date(1472933470783)\/","LastLoginDateUtc":"\/Date(1477522483903)\/","LastActivityDateUtc":"\/Date(1477523996553)\/","ExternalAuthenticationRecords":[],"ShoppingCartItems":[{"Id":1,"StoreId":1,"ShoppingCartTypeId":1,"CustomerId":1,"ProductId":18,"AttributesXml":null,"CustomerEnteredPrice":0.0000,"Quantity":1,"CreatedOnUtc":"\/Date(1473801903447)\/","UpdatedOnUtc":"\/Date(1473803336207)\/","IsFreeShipping":false,"IsShipEnabled":true,"AdditionalShippingCharge":0.0000,"IsTaxExempt":false}]}]}
I created these classes from the recommendation given in this link:
recommendation
I used this to create the classes: json2csharp
Response class:
class Response
{
bool success;
IList<Customer> data;
}
Customer class:
class Customer
{
public int Id { get; set; }
public string CustomerGuid { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public List<CustomerRole> CustomerRoles { get; set; }
public object AdminComment { get; set; }
public bool IsTaxExempt { get; set; }
public int AffiliateId { get; set; }
public int VendorId { get; set; }
public bool HasShoppingCartItems { get; set; }
public bool Active { get; set; }
public bool Deleted { get; set; }
public bool IsSystemAccount { get; set; }
public object SystemName { get; set; }
public string LastIpAddress { get; set; }
public DateTime CreatedOnUtc { get; set; }
public DateTime? LastLoginDateUtc { get; set; }
public DateTime LastActivityDateUtc { get; set; }
public List<object> ExternalAuthenticationRecords { get; set; }
public List<object> ShoppingCartItems { get; set; }
}
CustomerRole class:
class CustomerRole
{
public int Id { get; set; }
public string Name { get; set; }
public string SystemName { get; set; }
}
ExternalAuthenticationRecord class:
class ExternalAuthenticationRecord
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string Email { get; set; }
public object ExternalIdentifier { get; set; }
public object ExternalDisplayIdentifier { get; set; }
public object OAuthToken { get; set; }
public object OAuthAccessToken { get; set; }
public string ProviderSystemName { get; set; }
}
ShoppingCartItem class:
class ShoppingCartItem
{
public int Id { get; set; }
public int StoreId { get; set; }
public int ShoppingCartTypeId { get; set; }
public int CustomerId { get; set; }
public int ProductId { get; set; }
public object AttributesXml { get; set; }
public double CustomerEnteredPrice { get; set; }
public int Quantity { get; set; }
public DateTime CreatedOnUtc { get; set; }
public DateTime UpdatedOnUtc { get; set; }
public bool IsFreeShipping { get; set; }
public bool IsShipEnabled { get; set; }
public double AdditionalShippingCharge { get; set; }
public bool IsTaxExempt { get; set; }
}
I am using this statement to deserialzie the Json string: Response res = (Response)JsonConvert.DeserializeObject(customerJson, (typeof(Response)));
When I stop it in the debugger, it shows "res" as data: null and success: false.
I am not getting any errors. It is just not giving me the data from the Json string.
Any help that anybody can provide to figure out why I'm not getting the data I want in "res", would be gratefully appreciated.
Thanks,
Tony
The problem is related to the accessibility level in your Response class. By default the fields, property and method are private so JsonConvert is not able to fill the properties.
Change the class as follow:
class Response
{
public bool success {get; set;}
public IList<Customer> data {get; set;}
}
And it wil works.
Another improvement is related to the JsonConvert use. To avoid the explicit cast use this type conversion: JsonConvert.DeserializeObject<T>(string) where T will be Response

C# JSON Object wont deserialize

So I have been able to get JSON objects for a few things, however this object is quite a bit more complex.
I'm trying to get comments from Reddit.
Here is the method I use:
public async Task<List<string>> GetComments(string currentSubreddit, string topicID)
{
string commentUrl = "http://www.reddit.com/r/" + currentSubreddit + "/comments/" + topicID + "/.json";
List<Comments> commentList = new List<Comments>();
string jsonText = await wc.GetJsonText(commentUrl);
Comments.RootObject deserializeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Comments.RootObject>(jsonText);
List<string> commentListTest = new List<string>();
//List<string> commentListTest = deserializeObject.data.children[0].data.children;
return commentListTest;
}
This is the GetJsonText method:
public async Task<string> GetJsonText(string url)
{
var request = WebRequest.Create(url);
string text;
request.ContentType = "application/json; charset=utf-8";
var response = (HttpWebResponse)await request.GetResponseAsync();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return text;
}
And here is a link to the Object: http://pastebin.com/WQ8XXGNA
And a link to the jsonText: http://pastebin.com/7Kh6cA9a
The error returned says this:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in mscorlib.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JuicyReddit.Comments+RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I'd appreciate if anybody could help me with figuring out whats wrong with this.
Thanks
There are a few problems with your code actually
public async Task<List<string>> GetComments(string currentSubreddit, string topicID)
You don't need to return a list of string here, u need to return a full object
First rename RootObject in the model to an appropriate name such as "CommentsObject"
So set up your class like so and name it CommentsObject.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YOURNAMESPACE.Comments
{
public class MediaEmbed
{
}
public class SecureMediaEmbed
{
}
public class Data4
{
public int count { get; set; }
public string parent_id { get; set; }
public List<string> children { get; set; }
public string name { get; set; }
public string id { get; set; }
public string subreddit_id { get; set; }
public object banned_by { get; set; }
public string subreddit { get; set; }
public object likes { get; set; }
public object replies { get; set; }
public bool? saved { get; set; }
public int? gilded { get; set; }
public string author { get; set; }
public object approved_by { get; set; }
public string body { get; set; }
public object edited { get; set; }
public object author_flair_css_class { get; set; }
public int? downs { get; set; }
public string body_html { get; set; }
public string link_id { get; set; }
public bool? score_hidden { get; set; }
public double? created { get; set; }
public object author_flair_text { get; set; }
public double? created_utc { get; set; }
public object distinguished { get; set; }
public object num_reports { get; set; }
public int? ups { get; set; }
}
public class Child2
{
public string kind { get; set; }
public Data4 data { get; set; }
}
public class Data3
{
public string modhash { get; set; }
public List<Child2> children { get; set; }
public object after { get; set; }
public object before { get; set; }
}
public class Replies
{
public string kind { get; set; }
public Data3 data { get; set; }
}
public class Data2
{
public string domain { get; set; }
public object banned_by { get; set; }
public MediaEmbed media_embed { get; set; }
public string subreddit { get; set; }
public object selftext_html { get; set; }
public string selftext { get; set; }
public object likes { get; set; }
public object secure_media { get; set; }
public object link_flair_text { get; set; }
public string id { get; set; }
public SecureMediaEmbed secure_media_embed { get; set; }
public bool clicked { get; set; }
public bool stickied { get; set; }
public string author { get; set; }
public object media { get; set; }
public int score { get; set; }
public object approved_by { get; set; }
public bool over_18 { get; set; }
public bool hidden { get; set; }
public string thumbnail { get; set; }
public string subreddit_id { get; set; }
public object edited { get; set; }
public object link_flair_css_class { get; set; }
public object author_flair_css_class { get; set; }
public int downs { get; set; }
public bool saved { get; set; }
public bool is_self { get; set; }
public string permalink { get; set; }
public string name { get; set; }
public double created { get; set; }
public string url { get; set; }
public object author_flair_text { get; set; }
public string title { get; set; }
public double created_utc { get; set; }
public int ups { get; set; }
public int num_comments { get; set; }
public bool visited { get; set; }
public object num_reports { get; set; }
public object distinguished { get; set; }
public Replies replies { get; set; }
public int? gilded { get; set; }
public string parent_id { get; set; }
public string body { get; set; }
public string body_html { get; set; }
public string link_id { get; set; }
public bool? score_hidden { get; set; }
public int? count { get; set; }
public List<string> children { get; set; }
}
public class Child
{
public string kind { get; set; }
public Data2 data { get; set; }
}
public class Data
{
public string modhash { get; set; }
public List<Child> children { get; set; }
public object after { get; set; }
public object before { get; set; }
}
public class CommentsObject
{
public string kind { get; set; }
public Data data { get; set; }
}
}
Make your namespace correct!
Then handle the request and deserialise into a list of commentobjects: (u can use the webclient instead of httpclient if you want, this is just an example)
private HttpClient client;
public async Task<List<CommentsObject>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync("http://www.reddit.com/r/AskReddit/comments/1ut6xc.json");
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
List<CommentsObject> comments = await JsonConvert.DeserializeObjectAsync<List<CommentsObject>>(json);
return comments;
}
else
{
throw new Exception("Errorhandling message");
}
}
It's not ideal (and not completely an answer but more of a work around) but I created models that mock the reddit response json to make deserialization super easy. I use JsonProperty attributes on my model properties to pretty up the models a bit.
Here are the models
And since my models directly mock the json I can just use json.net's generic deserialize method.

Categories