JSON Web Request string to parsed data with JSON.NET - c#

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?

Related

Crestron Deserialize in C# and send array to Simpl+

Trying best how to take the following classes and deserialize a Json file to return each class values back to Simpl+. I am able to receive the Total value but anything in a list I am at a lost.
public class Client
{
public string clientId { get; set; }
public string locale { get; set; }
public string location { get; set; }
public string auxiliaryId { get; set; }
public string description { get; set; }
public string type { get; set; }
public string typeDescription { get; set; }
public Hardware hardware { get; set; }
public Network network { get; set; }
}
public class Hardware
{
public string type { get; set; }
public string softwareVersion { get; set; }
public string serialNumber { get; set; }
public string hardwareVersion { get; set; }
public string model { get; set; }
}
public class Network
{
public string ip { get; set; }
public string mac { get; set; }
public object homepage { get; set; }
public string dhcpSubnet { get; set; }
}
public class Result
{
public List<Client> clients { get; set; }
public string total { get; set; }
public int limit { get; set; }
public int page { get; set; }
}
public class Root
{
public string jsonrpc { get; set; }
public object id { get; set; }
public Result result { get; set; }
}
I was able to resolve this by adding the following to the foreach statement:
args.MyIndex = (ushort)(rootObject.TriplePlayResult.clients.IndexOf(item) + 1);

How to parse specific data from JSON response [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 5 years ago.
I am trying to parse JSON response using newtownsoft.json trying to parse the followers count and writeline.
This is the code:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
namespace J2C
{
class Checker
{
static void Main(string[] args)
{
var client = new WebClient();
var text = client.DownloadString("https://www.instagram.com/2saleapp/?__a=1");
User userObject = JsonConvert.DeserializeObject<User>(text);
Console.WriteLine("Followers count =" + userObject.followed_by);
Console.ReadKey();
}
}
}
and this is the API response:
{
"user": {
"biography": "Install 2Sale app to post your AD instantly!\nSnap, post, and sell. Its time to sale.",
"blocked_by_viewer": false,
"country_block": false,
"external_url": "http://autoigs.com/2sale_install",
"external_url_linkshimmed": "http://l.instagram.com/?u=http%3A%2F%2Fautoigs.com%2F2sale_install&e=ATMoKdz87_iz044M0ebrfU95WQT7JqBpnlGiGH9UDOsn7dRax7G6ZMxjh7wMuHY",
"followed_by": {
"count": 6511
},
"followed_by_viewer": false,
"follows": {
"count": 19
},
I just want to WriteLine Followed_by count numbers.
Any one can help me?
thank you
Copy the raw json to the clipboard. In Visual Studio menu select Edit > Paste Special > Paste JSON As Classes (this item is present at least since version VS2015. For earlier versions see). This will generate a set of classes.
public class Rootobject
{
public User user { get; set; }
public string logging_page_id { get; set; }
}
public class User
{
public string biography { get; set; }
public bool blocked_by_viewer { get; set; }
public bool country_block { get; set; }
public string external_url { get; set; }
public string external_url_linkshimmed { get; set; }
public Followed_By followed_by { get; set; }
public bool followed_by_viewer { get; set; }
public Follows follows { get; set; }
public bool follows_viewer { get; set; }
public string full_name { get; set; }
public bool has_blocked_viewer { get; set; }
public bool has_requested_viewer { get; set; }
public string id { get; set; }
public bool is_private { get; set; }
public bool is_verified { get; set; }
public string profile_pic_url { get; set; }
public string profile_pic_url_hd { get; set; }
public bool requested_by_viewer { get; set; }
public string username { get; set; }
public object connected_fb_page { get; set; }
public Media media { get; set; }
}
public class Followed_By
{
public int count { get; set; }
}
public class Follows
{
public int count { get; set; }
}
public class Media
{
public Node[] nodes { get; set; }
public int count { get; set; }
public Page_Info page_info { get; set; }
}
public class Page_Info
{
public bool has_next_page { get; set; }
public string end_cursor { get; set; }
}
public class Node
{
public string __typename { get; set; }
public string id { get; set; }
public bool comments_disabled { get; set; }
public Dimensions dimensions { get; set; }
public object gating_info { get; set; }
public string media_preview { get; set; }
public Owner owner { get; set; }
public string thumbnail_src { get; set; }
public object[] thumbnail_resources { get; set; }
public bool is_video { get; set; }
public string code { get; set; }
public int date { get; set; }
public string display_src { get; set; }
public string caption { get; set; }
public Comments comments { get; set; }
public Likes likes { get; set; }
public int video_views { get; set; }
}
public class Dimensions
{
public int height { get; set; }
public int width { get; set; }
}
public class Owner
{
public string id { get; set; }
}
public class Comments
{
public int count { get; set; }
}
public class Likes
{
public int count { get; set; }
}
Next, use the Rootobject. It's supposed to work.
var client = new WebClient();
var text = client.DownloadString("https://www.instagram.com/2saleapp/?__a=1");
Rootobject rootObject = JsonConvert.DeserializeObject<Rootobject>(text);
Console.WriteLine("Followers count =" + rootObject.user.followed_by.count);
In general, you should change the naming to conform to the generally accepted naming rules. You should use the JsonProperty attribute.
public class Rootobject
{
[JsonProperty("user")]
public User User { get; set; }
[JsonProperty("logging_page_id")]
public string LoggingPageId { get; set; }
}
And so on.
Create a class with name User in order to deserialize json string to User.
public class User
{
public string biography { get; set; }
public bool blocked_by_viewer { get; set; }
public bool country_block { get; set; }
public string external_url { get; set; }
public string external_url_linkshimmed { get; set; }
public FollowedBy followed_by { get; set; }
public string followed_by_viewer { get; set; }
public Follow follows { get; set; }
}
public class FollowedBy
{
public int count { get; set; }
}
public class Follow
{
public int count { get; set; }
}
After getting json string result using the below line for DeserializeObject to User and then assign it to new User object , after that use userObject for showing result.
User userObject = JsonConvert.DeserializeObject<User>(jsonString);
Now you have a user object that fill property with the API response.

JsonConvert.DeserializeObject not working sometimes

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...)

GeoJson c# example parse countries in the world and generate Geojson for each country

Looking for an example of how to parse / deserialize Geojson files using geojson.net. for some reason there are no examples of how to use the geojson.net package.
I would like to use this on my site with the google maps api. currently I use polygon shapes but want to move towards using geojson objects for the layers as this seems to be a better format.
using c# I would like to serialize Geojson, select specific country borders and generate a new geojson file that can be references and added to google maps as a layer.
to test this I created a colsole app to try to deserilaize the GeoJson, this does not work (please could you give me some direction on the correct way to deserialize Geojson ?)
static void Main(string[] args)
{
string Jsonstring = File.ReadAllText("c:/worldborders.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
List<GeoJsonProperties> ns = (List<GeoJsonProperties>)ser.Deserialize(Jsonstring, typeof(List<GeoJsonProperties>));
?ns is Empty?
}
I created a class for the geojson file using the online generator http://json2csharp.com/ (I had thought that GeoJson.net would include the class as its a standard) , GeoJsonProperties,
public class GeoJsonProperties
{
public int scalerank { get; set; }
public string featurecla { get; set; }
public double labelrank { get; set; }
public string sovereignt { get; set; }
public string sov_a3 { get; set; }
public double adm0_dif { get; set; }
public double level { get; set; }
public string type { get; set; }
public string admin { get; set; }
public string adm0_a3 { get; set; }
public double geou_dif { get; set; }
public string geounit { get; set; }
public string gu_a3 { get; set; }
public double su_dif { get; set; }
public string subunit { get; set; }
public string su_a3 { get; set; }
public double brk_diff { get; set; }
public string name { get; set; }
public string name_long { get; set; }
public string brk_a3 { get; set; }
public string brk_name { get; set; }
public object brk_group { get; set; }
public string abbrev { get; set; }
public string postal { get; set; }
public string formal_en { get; set; }
public string formal_fr { get; set; }
public string note_adm0 { get; set; }
public string note_brk { get; set; }
public string name_sort { get; set; }
public string name_alt { get; set; }
public double mapcolor7 { get; set; }
public double mapcolor8 { get; set; }
public double mapcolor9 { get; set; }
public double mapcolor13 { get; set; }
public double pop_est { get; set; }
public double gdp_md_est { get; set; }
public double pop_year { get; set; }
public double lastcensus { get; set; }
public double gdp_year { get; set; }
public string economy { get; set; }
public string income_grp { get; set; }
public double wikipedia { get; set; }
public object fips_10 { get; set; }
public string iso_a2 { get; set; }
public string iso_a3 { get; set; }
public string iso_n3 { get; set; }
public string un_a3 { get; set; }
public string wb_a2 { get; set; }
public string wb_a3 { get; set; }
public double woe_id { get; set; }
public string adm0_a3_is { get; set; }
public string adm0_a3_us { get; set; }
public double adm0_a3_un { get; set; }
public double adm0_a3_wb { get; set; }
public string continent { get; set; }
public string region_un { get; set; }
public string subregion { get; set; }
public string region_wb { get; set; }
public double name_len { get; set; }
public double long_len { get; set; }
public double abbrev_len { get; set; }
public double tiny { get; set; }
public double homepart { get; set; }
}
public class Geometry
{
public string type { get; set; }
public List<List<List<object>>> coordinates { get; set; }
}
public class Feature
{
public string type { get; set; }
public GeoJsonProperties properties { get; set; }
public Geometry geometry { get; set; }
}
public class RootObject
{
public string type { get; set; }
public List<Feature> features { get; set; }
}
}
GeoJSON.Net works with Newtonsoft.Json. you can deserialize the same way you would using that library.
var geoJsonObject = JsonConvert.DeserializeObject<Point>(json);
For deserializing a FeatureCollection object (like the one you mention in the question) using the GeoJSON.Net library use the following code :
var collection = JsonConvert.DeserializeObject<FeatureCollection>(json);

Could not cast or convert from {null} to system.Int32 in JSON response C#

I'm getting the following exception when using this bit of code to deserialize a JSON response from CrunchBase. The weird thing is it only happens to certain pages that are being deserialized even though both the results that work fine and the ones that don't both have empty [], empty"", and null values in key:value pairs. How can I cast or correct my mistake?
Exception gets thrown here:
JsonSerializer serializer = new JsonSerializer();
RootObject ro = JsonConvert.DeserializeObject<RootObject>(response);
The inner exception is:
InnerException:
Message=Could not cast or convert from {null} to System.Int32.
Source=Newtonsoft.Json
Thanks for your eyes in advance!
Update:
as asked for the structure of the root object and the additional objects on that JSON endpoint. These were generated by http://json2csharp.com/ after putting the URL of the JSON endpoint into it.
The JSON is long so here are two example links: this one works without error http://api.crunchbase.com/v/1/company/kiip.js , while this other (and others) throws the exception http://api.crunchbase.com/v/1/company/tata-communications.js
public class Image
{
public List<List<object>> available_sizes { get; set; }
public object attribution { get; set; }
}
public class Person
{
public string first_name { get; set; }
public string last_name { get; set; }
public string permalink { get; set; }
}
public class Relationship
{
public bool is_past { get; set; }
public string title { get; set; }
public Person person { get; set; }
}
public class Provider
{
public string name { get; set; }
public string permalink { get; set; }
}
public class Providership
{
public string title { get; set; }
public bool is_past { get; set; }
public Provider provider { get; set; }
}
public class FinancialOrg
{
public string name { get; set; }
public string permalink { get; set; }
}
public class Person2
{
public string first_name { get; set; }
public string last_name { get; set; }
public string permalink { get; set; }
}
public class Investment
{
public object company { get; set; }
public FinancialOrg financial_org { get; set; }
public Person2 person { get; set; }
}
public class FundingRound
{
public string round_code { get; set; }
public string source_url { get; set; }
public string source_description { get; set; }
public double raised_amount { get; set; }
public string raised_currency_code { get; set; }
public int funded_year { get; set; }
public int funded_month { get; set; }
public int funded_day { get; set; }
public List<Investment> investments { get; set; }
}
public class Office
{
public string description { get; set; }
public string address1 { get; set; }
public string address2 { get; set; }
public string zip_code { get; set; }
public string city { get; set; }
public string state_code { get; set; }
public string country_code { get; set; }
public object latitude { get; set; }
public object longitude { get; set; }
}
public class VideoEmbed
{
public string embed_code { get; set; }
public string description { get; set; }
}
public class Screenshot
{
public List<List<object>> available_sizes { get; set; }
public object attribution { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string permalink { get; set; }
public string crunchbase_url { get; set; }
public string homepage_url { get; set; }
public string blog_url { get; set; }
public string blog_feed_url { get; set; }
public string twitter_username { get; set; }
public string category_code { get; set; }
public int number_of_employees { get; set; }
public int founded_year { get; set; }
public int founded_month { get; set; }
public object founded_day { get; set; }
public object deadpooled_year { get; set; }
public object deadpooled_month { get; set; }
public object deadpooled_day { get; set; }
public object deadpooled_url { get; set; }
public string tag_list { get; set; }
public string alias_list { get; set; }
public string email_address { get; set; }
public string phone_number { get; set; }
public string description { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string overview { get; set; }
public Image image { get; set; }
public List<object> products { get; set; }
public List<Relationship> relationships { get; set; }
public List<object> competitions { get; set; }
public List<Providership> providerships { get; set; }
public string total_money_raised { get; set; }
public List<FundingRound> funding_rounds { get; set; }
public List<object> investments { get; set; }
public object acquisition { get; set; }
public List<object> acquisitions { get; set; }
public List<Office> offices { get; set; }
public List<object> milestones { get; set; }
public object ipo { get; set; }
public List<VideoEmbed> video_embeds { get; set; }
public List<Screenshot> screenshots { get; set; }
public List<object> external_links { get; set; }
}
Json.NET supports JSON Schema. You could create a schema with all the required properties marked and validate incoming JSON against it before deserializing. In this you can check if value is null you can make change it to some default value.
Hope this works for you.

Categories

Resources