I want to insert into my class data from JSON but I got a Newtonsoft.Json.JsonSerializationException.
My PlayerStats class is good, I think, and I don't know why it's not working.
I can download and print JSON to the console but my code stops working at the point when I try to deserialize. I tried to add settings to deserialize but it's still not working.
Here is my code:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Net;
namespace DiscordBot
{
class Osu
{
public string _nickname;
private string _key = "key";
public class PlayerStats
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("username")]
public string UserName { get; set; }
[JsonProperty("count300")]
public int Count300 { get; set; }
[JsonProperty("count100")]
public int Count100 { get; set; }
[JsonProperty("count50")]
public int Count50 { get; set; }
[JsonProperty("playcount")]
public int PlayCount { get; set; }
[JsonProperty("ranked_score")]
public long RankedScore { get; set; }
[JsonProperty("total_score")]
public long TotalScore { get; set; }
[JsonProperty("pp_rank")]
public int PpRank { get; set; }
[JsonProperty("level")]
public double Level { get; set; }
[JsonProperty("pp_raw")]
public double RawPp { get; set; }
[JsonProperty("accuracy")]
public double Accuracy { get; set; }
[JsonProperty("count_rank_ss")]
public int CountRankSs { get; set; }
[JsonProperty("count_rank_ssh")]
public int CoundRankSsh { get; set; }
[JsonProperty("count_rank_s")]
public int CountRankS { get; set; }
[JsonProperty("count_rank_sh")]
public int CountRankSh { get; set; }
[JsonProperty("count_rank_a")]
public int CountRankA { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("pp_country_rank")]
public int PpCountryRank { get; set; }
}
public PlayerStats GetUserStats()
{
string json = string.Empty;
var result = JsonConvert.DeserializeObject<PlayerStats>(json);
try
{
string url = #"https://osu.ppy.sh/api/get_user";
using (WebClient wc = new WebClient())
{
wc.QueryString.Add("k", _key);
wc.QueryString.Add("u", _nickname);
wc.QueryString.Add("m", "0");
json = wc.DownloadString(url);
Console.WriteLine(json);
result = JsonConvert.DeserializeObject<PlayerStats>(json);
return result;
}
}
catch (WebException ex)
{
Console.WriteLine("Osu Error: " + ex.Status);
}
return result;
}
}
}
JSON:
[
{
"user_id":"10415972"
,"username":"iGruby"
,"count300":"851431"
,"count100":"15449 6"
,"count50":"19825"
,"playcount":"7129"
,"ranked_score":"453511877"
,"total_score" :"2735863526"
,"pp_rank":"147461"
,"level":"74.5611"
,"pp_raw":"1642.73"
,"accuracy" :"94.46521759033203"
,"count_rank_ss":"13"
,"count_rank_ssh":"2"
,"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"
,"events":[]
}
]
Refer this Tested Answer from the file I have loaded your json and DeserializeObject check my model also and how I am DeserializeObject
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string data = File.ReadAllText("D://readjson.txt");
var obj = JsonConvert.DeserializeObject<List<RootObject>>(data);
}
}
public class RootObject
{
public string user_id { get; set; }
public string username { get; set; }
public string count300 { get; set; }
public string count100 { get; set; }
public string count50 { get; set; }
public string playcount { get; set; }
public string ranked_score { get; set; }
public string total_score { get; set; }
public string pp_rank { get; set; }
public string level { get; set; }
public string pp_raw { get; set; }
public string accuracy { get; set; }
public string count_rank_ss { get; set; }
public string count_rank_ssh { get; set; }
public string count_rank_s { get; set; }
public string count_rank_sh { get; set; }
public string count_rank_a { get; set; }
public string country { get; set; }
public string pp_country_rank { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<object> events { get; set; }
}
}
Pp_country_rank and count_rank_s contains a space. This is trying to be parsed to an integer.
"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"
Related
public List<CoinMarket> GetCoinMarket()
{
List<CoinMarket> coinMarket = new List<CoinMarket>();
var URLWebAPI = "http://190.202.54.19/wsZeus/api/Account/Markets/Get";
try
{
using (var Client = new System.Net.Http.HttpClient())
{
var JSON = Client.GetStringAsync(URLWebAPI);
coinMarket = (List<CoinMarket>)Newtonsoft.Json.JsonConvert.DeserializeObject(JSON.Result);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(#" ERROR {0}", ex.Message);
}
return coinMarket;
}
It is throwing and i do not know why. It looks like there is something wrong with the serialization part. But i verified it.
You are using json deserializer incorrectly. DeserializeObject returns custom object which is not castable to your List<T>. This output:
Newtonsoft.Json.Linq.JArray
SO20171129.CoinData[]
System.Collections.Generic.List`1[SO20171129.CoinData]
is the result of this code.
class Program
{
static void Main(string[] args)
{
// returns Newtonsoft.Json.Linq.JArray
var coinMarket = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText("get.json"));
Console.WriteLine(coinMarket.GetType());
// returns array of CoinData
var coinMarketTyped = Newtonsoft.Json.JsonConvert.DeserializeObject<CoinData[]>(File.ReadAllText("get.json"));
Console.WriteLine(coinMarketTyped.GetType());
// returns List of CoinData
var coinMarketTyped2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CoinData>>(File.ReadAllText("get.json"));
Console.WriteLine(coinMarketTyped2.GetType());
}
}
public class CoinData
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
public string price_btc { get; set; }
public string __invalid_name__24h_volume_usd { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
My guess is that your json structure members do not match the CoinMarket class members.
What I would do is to copy the json result and generate the corresponding CoinMarket class on the following website: http://json2csharp.com/
It will output the right CoinMarket class for you.
public class CoinMarket
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
public string price_btc { get; set; }
[JsonProperty("24h_volume_usd")]
public string h_volume_usd { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
}
This is my CoinMarket Class
I am trying to (serialise?) a class in to JSON and am getting a null reference exception - please can you help me understand why and possible fix this?
I wrote a class which contains several nested classes (the JSON structure was provided by the UK carrier DPD).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DPDJSONLibrary
{
public class DPD_JSON
{
// insert shipment request
/// <summary>
/// Root Object. Insert Shipment Request
/// </summary>
public class IS
{
public string job_id { get; set; }
public bool collectionOnDelivery { get; set; }
public IS_Invoice invoice { get; set; }
public string collectionDate { get; set; }
public bool consolidate { get; set; }
public IS_Consignment consignment { get; set; }
}
public class IS_Address
{
public string addressId { get; set; }
public string countryCode { get; set; }
public string countryName { get; set; }
public string county { get; set; }
public string locality { get; set; }
public string organisation { get; set; }
public string postcode { get; set; }
public string street { get; set; }
public string town { get; set; }
}
public class IS_ContactDetails
{
public string contactName { get; set; }
public string telephone { get; set; }
}
public class IS_PickupLocation
{
public IS_Address address { get; set; }
public bool allowRemotePickup { get; set; }
public string pickupLocationCode { get; set; }
}
public class IS_NotificationDetails
{
public string email { get; set; }
public string mobile { get; set; }
}
public class IS_ParcelProduct
{
public string countryOfOrigin { get; set; }
public Int32 numberOfItems { get; set; }
public string productCode { get; set; }
public string productFabricContent { get; set; }
public string productHarmonisedCode { get; set; }
public string productItemsDescription { get; set; }
public string productTypeDescription { get; set; }
public decimal unitValue { get; set; }
public decimal unitWeight { get; set; }
}
public class IS_InvoiceItem
{
public string countryOfOrigin { get; set; }
public string itemCode { get; set; }
public string itemDescription { get; set; }
public int numberOfItems { get; set; }
public decimal unitValue { get; set; }
}
public class IS_InvoiceBillingDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
public string vatNumber { get; set; }
}
public class IS_Invoice
{
public string countryOfOrigin { get; set; }
public IS_InvoiceBillingDetails invoiceBillingDetails { get; set; }
public string invoiceCustomsNumber { get; set; }
public string invoiceExportReason { get; set; }
public bool invoiceIsDeclared { get; set; }
public IS_InvoiceItem invoiceItem { get; set; }
public string invoiceTermsOfDelivery { get; set; }
public int invoiceType { get; set; }
public int totalItems { get; set; }
public decimal totalValue { get; set; }
public decimal totalWeight { get; set; }
}
public class IS_DeliveryDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
public IS_NotificationDetails notificationDetails { get; set; }
public IS_PickupLocation deliveryDetails { get; set; }
}
public class IS_CollectionDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
}
public class IS_Parcels
{
public bool isVoided { get; set; }
public string labelNumber { get; set; }
public int packageNumber { get; set; }
public string parcelNumber { get; set; }
public IS_ParcelProduct parcelProduct { get; set; }
public string parcelnetBarcode { get; set; }
public string parcelnetData { get; set; }
public string parcelnetLabelNumber { get; set; }
}
public class IS_Consignment
{
public IS_CollectionDetails collectionDetails { get; set; }
public string consignmentNumber { get; set; }
public string consignmentRef { get; set; }
public decimal? customsValue { get; set; }
public IS_DeliveryDetails deliveryDetails { get; set; }
public string deliveryInstructions { get; set; }
public bool liability { get; set; }
public decimal liabilityValue { get; set; }
public string networkCode { get; set; }
public int numberOfParcels { get; set; }
public IS_Parcels parcel { get; set; }
public string parceldescription { get; set; }
public string shippingRef1 { get; set; }
public string shippingRef2 { get; set; }
public string shippingRef3 { get; set; }
public decimal totalWeight { get; set; }
}
}
}
I have another class containing public variables which I assign values to from code, and a method/function to instantiate my JSON class and pull in the values from the public variables.
I am getting a null reference exception on the line:
NewShipmentObject.consignment.consignmentNumber = null;
The error reads:
error System.NullReferenceException: Object reference not set to an instance of an object
The method I cam calling and getting the error in is below:
using System;
using System.Text;
using System.Net;
// include
using System.IO;
using System.Web.UI.WebControls;
using DPDJSONLibrary;
using System.Web;
using Newtonsoft.Json;
namespace DPDAPILibrary
{
public class DPD_API
{
#region public class variables
public string BusinessUnit;
public string DeliveryDirection;
public string NumberOfParcels;
public string ShipmentType;
public string TotalWeight;
public string CollectionDate;
public string ColName;
public string ColPhone;
public string ColOrganisation;
public string ColCountryCode;
public string ColPostCode;
public string ColStreet;
public string ColLocality;
public string ColTown;
public string ColCounty;
public string DelName;
public string DelPhone;
public string DelOrganisation;
public string DelCountryCode;
public string DelPostcode;
public string DelStreet;
public string DelLocality;
public string DelTown;
public string DelCounty;
public string DelNotificationEmail;
public string DelNotificationMobile;
public string NetworkCode;
public string ShippingRef1;
public string ShippingRef2;
public string ShippingRef3;
public string CustomsValue;
public string DeliveryInstructions;
public string ParcelDescription;
public string LiabilityValue;
public string Liability;
#endregion
public Boolean insertShipment(out string JSONData)
{
try
{
DPD_JSON.IS NewShipmentObject = new DPD_JSON.IS();
NewShipmentObject.job_id = null;
NewShipmentObject.collectionOnDelivery = false;
NewShipmentObject.invoice = null;
NewShipmentObject.collectionDate = CollectionDate;
NewShipmentObject.consolidate = false;
NewShipmentObject.consignment.consignmentNumber = null;
NewShipmentObject.consignment.consignmentRef = null;
NewShipmentObject.consignment.parcel = null;
NewShipmentObject.consignment.collectionDetails.contactDetails.contactName = ColName;
NewShipmentObject.consignment.collectionDetails.contactDetails.telephone = ColPhone;
NewShipmentObject.consignment.collectionDetails.address.organisation = ColOrganisation;
NewShipmentObject.consignment.collectionDetails.address.countryCode = ColCountryCode;
NewShipmentObject.consignment.collectionDetails.address.postcode = ColPostCode;
NewShipmentObject.consignment.collectionDetails.address.street = ColStreet;
NewShipmentObject.consignment.collectionDetails.address.locality = ColLocality;
NewShipmentObject.consignment.collectionDetails.address.town = ColTown;
NewShipmentObject.consignment.collectionDetails.address.county = ColCounty;
NewShipmentObject.consignment.deliveryDetails.contactDetails.contactName = ColName;
NewShipmentObject.consignment.deliveryDetails.contactDetails.telephone = DelPhone;
NewShipmentObject.consignment.deliveryDetails.address.organisation = DelOrganisation;
NewShipmentObject.consignment.deliveryDetails.address.countryCode = DelCountryCode;
NewShipmentObject.consignment.deliveryDetails.address.postcode = DelPostcode;
NewShipmentObject.consignment.deliveryDetails.address.street = DelStreet;
NewShipmentObject.consignment.deliveryDetails.address.locality = DelLocality;
NewShipmentObject.consignment.deliveryDetails.address.town = DelTown;
NewShipmentObject.consignment.deliveryDetails.address.county = DelCounty;
NewShipmentObject.consignment.deliveryDetails.notificationDetails.email = DelNotificationEmail;
NewShipmentObject.consignment.deliveryDetails.notificationDetails.mobile = DelNotificationMobile;
// default output value
JSONData = "";
JSONData = Convert.ToString(JsonConvert.SerializeObject(NewShipmentObject));
}
catch (Exception ex)
{
JSONData = Convert.ToString(ex);
return false;
}
}
}
}
You'll need to initialize all objects (including child entities) before you can use them*, as they will otherwise adopt their default values (which will be null for objects). i.e. replace
NewShipmentObject.consignment.consignmentNumber = null;
with:
NewShipmentObject.consignment = new IS_Consignment();
NewShipmentObject.consignment.consignmentNumber = null;
You can save yourself a lot of typing - instead of line-by-line setting of each field, you can do so using Object Initializer Syntax:
var NewShipmentObject = new DPD_JSON.IS
{
job_id = null,
collectionOnDelivery = false,
consignment = new IS_Consignment
{
consignmentNumber = null,
... more consignment settings here
}
... etc.
It should be noted that you don't need to explicitly set uninitialized variables to their default value, i.e. both
job_id = null,
collectionOnDelivery = false
are redundant, as these should be the default values in any event.
* (unless this initialization is done automatically in the constructor)
I am using a C# LdapConnection to get a SearchResponse at work. I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse. The Json string is properly formatted. Am I using the Newtonsoft.Json library in the wrong way? Is there a better way to do this? My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.
My Console Application:
class Program
{
static void Main(string[] args)
{
LdapClient client = new LdapClient();
List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
string query = "(|(uupid=name1)(uupid=name2))";
string[] attributes = new string[] { };
string host = "id.directory.univ";
int port = 1234;
SearchResponse response = client.RawQuery(query, attributes, host, port);
string json = JsonConvert.SerializeObject(response);
var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
}
}
My DirectoryEntity Class:
public class DirectoryEntity
{
public string EntityDN { get; set; }
public int MailStop { get; set; }
public List<string> UniversityAffiliation { get; set; }
public int UniversityId { get; set; }
public string GivenName { get; set; }
public string Title { get; set; }
public string PasswordState { get; set; }
public string MiddleName { get; set; }
public string AccountState { get; set; }
public int Uid { get; set; }
public string Mail { get; set; }
public string MailPreferredAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public List<string> GroupMembership { get; set; }
public string DegreeType { get; set; }
public int ClassLevelCode { get; set; }
public string AuthId { get; set; }
public string Major { get; set; }
public string ClassLevel { get; set; }
public bool SupressDisplay { get; set; }
public string UnderGraduateLevel { get; set; }
public string ObjectClass { get; set; }
public int DepartmentNumber { get; set; }
public List<string> EduPersonAffiliation { get; set; }
public string LocalPostalAddress { get; set; }
public string Uupid { get; set; }
public string LocalPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Department { get; set; }
public string Sn { get; set; }
}
My DirectoryEntities Class:
public class DirectoryEntities
{
public List<DirectoryEntity> Entities { get; set; }
public int Count { get; set; }
}
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class:
public DirectoryEntity() { }
I'm trying to Deserialize some json using JsonConver.DeserializeObject. however it's not working on some json from the api I'm using. here is a link that does not work: https://api.pokemontcg.io/v1/cards?setCode=smp
and here is a link that does work. https://api.pokemontcg.io/v1/cards?setCode=sm2
I'm not sure why it sometimes works and sometimes not. The data that comes out of it is very similar to each other, just different cards.
Here is the code:
public static async Task<T> GetDataAsync<T>(this HttpClient client, string address, string querystring)
where T : class
{
var uri = address;
if (!string.IsNullOrEmpty(querystring))
{
uri += querystring;
}
var httpMessage = await client.GetStringAsync(uri);
var jsonObject = JsonConvert.DeserializeObject<T>(httpMessage);
return jsonObject;
}
Now my card class
namespace CardAppReal.Lib.Models
{
public class Card
{
public string id { get; set; }
public string name { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string supertype { get; set; } // if pokemon, trainer or energy
public string setcode { get; set; }
public int number { get; set; }
public string set { get; set; }
}
}
With a root
using System.Collections.Generic;
using CardAppReal.Lib.Models;
namespace CardAppReal.Lib.Entities
{
public class RootCard
{
public List<Card> cards { get; set; }
}
}
If u could help me out I would find it amazing.
I have tested your json.
this is the Model
namespace Test
{
public class Attack
{
public List<string> cost { get; set; }
public string name { get; set; }
public string text { get; set; }
public string damage { get; set; }
public int convertedEnergyCost { get; set; }
}
public class Weakness
{
public string type { get; set; }
public string value { get; set; }
}
public class Resistance
{
public string type { get; set; }
public string value { get; set; }
}
public class Ability
{
public string name { get; set; }
public string text { get; set; }
public string type { get; set; }
}
public class Card
{
public string id { get; set; }
public string name { get; set; }
public int nationalPokedexNumber { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string subtype { get; set; }
public string supertype { get; set; }
public string hp { get; set; }
public List<string> retreatCost { get; set; }
public string number { get; set; }
public string artist { get; set; }
public string rarity { get; set; }
public string series { get; set; }
public string set { get; set; }
public string setCode { get; set; }
public List<string> types { get; set; }
public List<Attack> attacks { get; set; }
public List<Weakness> weaknesses { get; set; }
public List<Resistance> resistances { get; set; }
public string evolvesFrom { get; set; }
public Ability ability { get; set; }
public List<string> text { get; set; }
}
public class RootObject
{
public List<Card> cards { get; set; }
}
}
And this is how I call the Deserialize
RootObject root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(RootObject.WRONG_JSON);
(NB WRONG_JSON is your json string...)
I am using .net to call to a webservice then parse it to usable data.
Right now I am experimenting with this call: http://www.reddit.com/r/all.json
Which returns: http://pastebin.com/AbV4yVuC
This is put in to a string, which I called jsontxt.
I am using JSON.NET to parse the information but it doesn't seem to be working. I initially tried to deserialize it as an object and it didn't work as nothing is put in to the variable
Then I tried to deserialize it as a dataset and I'm having no luck again. My error was
An unhandled exception of type 'Newtonsoft.Json.JsonException' occurred in Newtonsoft.Json.dll
MY CODE:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tutorialresult1
{
class Program
{
static void Main(string[] args)
{
using (var webClient = new System.Net.WebClient())
{
var jsontxt = webClient.DownloadString("http://www.reddit.com/r/all.json");
// Console.Write(json);
// -----Deserializing by Object--------------
//MediaEmbed account = JsonConvert.DeserializeObject<MediaEmbed>(jsontxt);
//Console.WriteLine(account.width); //COMES OUT TO NULL
// -----Deserializing by DataSet--------------
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(jsontxt);
DataTable dataTable = dataSet.Tables["Children"];
Console.WriteLine(dataTable.Rows.Count);
}
}
public class MediaEmbed
{
public string content { get; set; }
public int width { get; set; }
public bool scrolling { get; set; }
public int height { get; set; }
}
.... //rest of classes here for each json which were generated with http://json2csharp.com/
}
}
I'm just trying to make the JSON easily accessible by parsing it.
Using json2charp I generated the following set of classes. Using those you should be able to deserialize the JSON into RootObject using JSON.NET.
var account = JsonConvert.DeserializeObject<RootObject>(jsontxt);
.
public class MediaEmbed
{
public string content { get; set; }
public int? width { get; set; }
public bool? scrolling { get; set; }
public int? height { get; set; }
}
public class Oembed
{
public string provider_url { get; set; }
public string description { get; set; }
public string title { get; set; }
public string url { get; set; }
public string type { get; set; }
public string author_name { get; set; }
public int height { get; set; }
public int width { get; set; }
public string html { get; set; }
public int thumbnail_width { get; set; }
public string version { get; set; }
public string provider_name { get; set; }
public string thumbnail_url { get; set; }
public int thumbnail_height { get; set; }
public string author_url { get; set; }
}
public class SecureMedia
{
public Oembed oembed { get; set; }
public string type { get; set; }
}
public class SecureMediaEmbed
{
public string content { get; set; }
public int? width { get; set; }
public bool? scrolling { get; set; }
public int? height { get; set; }
}
public class Oembed2
{
public string provider_url { get; set; }
public string description { get; set; }
public string title { get; set; }
public int thumbnail_width { get; set; }
public int height { get; set; }
public int width { get; set; }
public string html { get; set; }
public string version { get; set; }
public string provider_name { get; set; }
public string thumbnail_url { get; set; }
public string type { get; set; }
public int thumbnail_height { get; set; }
public string url { get; set; }
public string author_name { get; set; }
public string author_url { get; set; }
}
public class Media
{
public string type { get; set; }
public Oembed2 oembed { 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 string selftext_html { get; set; }
public string selftext { get; set; }
public object likes { get; set; }
public SecureMedia secure_media { get; set; }
public string link_flair_text { get; set; }
public string id { get; set; }
public int gilded { 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 Media 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 string 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 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 string after { get; set; }
public object before { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public Data data { get; set; }
}
You are trying to deserialize a json-string into a dataset-object. But the json-string doesn't have the format of a dataset. So you need to create a class which matches the json or deserialize it into a dictionary or sth. like this.
Have you tried deserialize using the following? Seems to be more robust for me.
using System.Web.Script.Serialization;
...
var x = new JavaScriptSerializer().Deserialize<Obj_type>(jsonstring);
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx
as purplej0kr mentioned you will need to have a .Net model to use for Obj_type (and it will need to match the object you are parsing) or this will not work.
You will need the System.Web.Extensions.dll referenced in your project (right click add reference, dll is usually under 'Assemblies'). Otherwise:
Where can I find the assembly System.Web.Extensions dll?