Newtonsoft Json Convert does not convert json string to object - c#

I have these classes
public class ResponseEntryInfoAndTollDue
{
public int Code { get; set; }
public string Message { get; set; }
public TagEntryInfo TagEntryInfo { get; set; }
public TollMatrix TollMatrix { get; set; }
public List<TagInfoParam> TagInfoParams { get; set; }
public ResponseEntryInfoAndTollDue()
{
TagEntryInfo = new TagEntryInfo();
TollMatrix = new TollMatrix();
TagInfoParams = new List<TagInfoParam>();
}
}
public class TagEntryInfo
{
public long TrxnID { get; set; }
public string TagRFIDNumber { get; set; }
public string EntryTrxnDTime { get; set; }
public int EntryPlaza { get; set; }
public short EntryLane { get; set; }
public string EntryDirection { get; set; }
public string EntryLaneType { get; set; }
public string PostingDateTime { get; set; }
public string Action { get; set; }
}
public class TollMatrix
{
public decimal TollDue { get; set; }
public decimal TollVat { get; set; }
public decimal TollNoVat { get; set; }
public bool IsDefaulted { get; set; }
}
public class TagInfoParam
{
public DateTime? AsOfDate { get; set; }
public Decimal? AvailableBalance { get; set; }
public string TagNumber { get; set; }
public string PLateNumber { get; set; }
public Int16 HonorPlate { get; set; }
public Int16 TagStatusID { get; set; }
public string TID { get; set; }
public string EPC { get; set; }
public string AccountTypeID { get; set; }
public Int16 AccountStatusID { get; set; }
public Int16 TagClassID { get; set; }
public Int16 Status { get; set; }
}
From a webservice I get this json string:
{"Result":{"Code":0,"Message":"With entry info computed toll due","TagEntryInfo":{"TrxnID":6666750,"TagRFIDNumber":"1234567890","EntryTrxnDTime":"2021-01-16 16:40:16.560","EntryPlaza":123,"EntryLane":1,"EntryDirection":"B","EntryLaneType":"A","PostingDateTime":"2021-01-16T16:43:16.05","Action":"A"},"TollMatrix":{"TollDue":164.0000,"TollVat":17.5700,"TollNoVat":146.4300,"IsDefaulted":false},"TagInfoParams":[{"AsOfDate":"2021-01-16T17:12:04.213","AvailableBalance":537.0000,"TagNumber":"1234567890","PLateNumber":"Q123","HonorPlate":1,"TagStatusID":1,"TID":"Elfkajs98","EPC":"889080990709","AccountTypeID":"REV","AccountStatusID":1,"TagClassID":1,"Status":1}]},"Id":351,"Exception":null,"Status":5,"IsCanceled":false,"IsCompleted":true,"CreationOptions":0,"AsyncState":null,"IsFaulted":false}
This is how I convert it:
var response = JsonConvert.DeserializeObject(ret);
I know that it doesn't get converted because this is what I get:
This is the result:
Why is this not being converted into an object?

As Fabio also mentioned that your json contains the attribute Result which is not part of your object so you can use below logic to deserialize
var jObj = JObject.Parse(json);
var responseEntryInfoAndTollDue = JsonConvert.DeserializeObject<ResponseEntryInfoAndTollDue>(jObj["Result"].ToString());
The above code first parse the Json to JObject and uses Result property to deserialize to ResponseEntryInfoAndTollDue object.
Check this fiddle - https://dotnetfiddle.net/7Pc3sJ

Related

Deserializing the JSON Objest results in all null fields C#

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

Access data in JSON C# Dynamic variable

I am working with processing/consuming some data from: https://ashesescalation-api-tachyon.stardock.net/v1/products/2641/leaderboards/ladder/de5bfc9a-9092-4014-b52e-89151de42646?offset=0&count=2 (which can be opened easily in Firefox to view.)
I am able to access the data in C# by doing this:
data being the json data...
dynamic players = JArray.Parse(data);
var p = players[0];
Console.Write(p.personaName);
However I am having trouble accessing the part in the JSON data: "dataInteger" for example the "totalUnitsKilled."
p.dataInteger[0].totalUnitsKilled
That "p.dataInteger[0].totalUnitsKilled" doesn't work.
How can I access that data in C#?
Thank you very much for your help.
Warren
See image in visual studio 1
See image in visual studio 2
Kinldy take a look at my comment in your question, base on that link you need to use JsonProperty to mapped the key that has special characters and manually named it based on your needs.
Anyways, you can do the following to achieved what you need.
Copy your link to http://json2csharp.com/
Copy the generated Quicktypes and paste it to your code.
Use JsonProperty to indicate attributes on your properties for the names and manually rename properties that contains invalid_name
And DeserializeObject the object.
Here is the code:
Declare the classes from the generated quicktypes.
public class DataInteger
{
[JsonProperty(PropertyName = "totalUnitsKilled ")]
public int totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
[JsonProperty(PropertyName = "substrate-TotalGamesPlayed")]
public int SubstrateTotalGamesPlayed { get; set; }
[JsonProperty(PropertyName = "phC-TotalGamesPlayed")]
public int PHCTotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}
public class RootObject
{
public string personaLadderId { get; set; }
public int rank { get; set; }
public string personaId { get; set; }
public string personaName { get; set; }
public string avatarUrl { get; set; }
public string avatarUrlSmall { get; set; }
public string avatarUrlMedium { get; set; }
public string avatarUrlLarge { get; set; }
public string ladderType { get; set; }
public string ladderId { get; set; }
public string seasonId { get; set; }
public int bracketId { get; set; }
public string bracketName { get; set; }
public int rankingScore { get; set; }
public int secondaryScore { get; set; }
public int ruleTypeId { get; set; }
public int wins { get; set; }
public int losses { get; set; }
public int ties { get; set; }
public int tieStreak { get; set; }
public int winStreak { get; set; }
public int lossStreak { get; set; }
public int longestTieStreak { get; set; }
public int longestWinStreak { get; set; }
public int longestLossStreak { get; set; }
public int bracketMaxScore { get; set; }
public int bracketScore { get; set; }
public DateTime updateDate { get; set; }
public int totalMatchesPlayed { get; set; }
public DataInteger dataInteger { get; set; }
}
Call the API (Magic begins here)
var httpClient = new HttpClient();
var link = $#"https://ashesescalation-api-tachyon.stardock.net/v1/products/2641/leaderboards/ladder/de5bfc9a-9092-4014-b52e-89151de42646?offset=0&count=2";
var response = await httpClient.GetAsync(link);
var contents = await response.Content.ReadAsStringAsync();
//deserialized json result object...
dynamic json = JsonConvert.DeserializeObject(contents);
foreach (var item in json)
{
//deserialized again the item
var data = JsonConvert.DeserializeObject<RootObject>(Convert.ToString(item));
//you can now access all the properties including dataInteger.
Console.WriteLine(Convert.ToString(data.dataInteger.totalUnitsKilled));
Console.WriteLine(Convert.ToString(data.dataInteger.totalTitansKilled));
}
Update:
If you don't want to use strongly typed class you can do parsing using JArray
JArray jsonVal = JArray.Parse(contents) as JArray;
dynamic items = jsonVal;
foreach (dynamic item in items)
{
var x = item.dataInteger;
//you can access the fields inside dataInteger.
Console.WriteLine(x["totalUnitsKilled "]);
Console.WriteLine(x["phC-TotalGamesPlayed"]);
Console.WriteLine(x["substrate-TotalGamesPlayed"]);
}
Hope this will help you.
As suggested by other users, there is a space in property name "totalUnitsKilled ", if you change it to "totalUnitsKilled". Below code will work fine:-
Console.WriteLine(p.dataInteger.totalUnitsKilled);
Your JSON string is wrong.
[{"personaLadderId":"371eaf1c-4cfe-4873-af41-56e0cb9fcf91","rank":1,"personaId":"55834d01-13f3-445e-861f-0bc4769d87cc","personaName":"Amelie","avatarUrl":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg","avatarUrlSmall":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg","avatarUrlMedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_medium.jpg","avatarUrlLarge":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg","ladderType":"Ranked","ladderId":"de5bfc9a-9092-4014-b52e-89151de42646","seasonId":"fd7dd807-4ac2-40ec-8476-a4b2937f70af","bracketId":0,"bracketName":"Legendary","rankingScore":38,"secondaryScore":2054,"ruleTypeId":1,"wins":374,"losses":32,"ties":0,"tieStreak":0,"winStreak":8,"lossStreak":0,"longestTieStreak":0,"longestWinStreak":61,"longestLossStreak":3,"bracketMaxScore":0,"bracketScore":0,"updateDate":"2018-03-03T14:13:09.647Z","totalMatchesPlayed":406,"dataInteger":{"totalUnitsKilled ":92615,"totalTitansKilled":14,"totalTimePlayed":294676,"substrate-TotalGamesPlayed":127,"phC-TotalGamesPlayed":6,"lastReplayVersion":265301040,"replayUploadedCount":160}},{"personaLadderId":"f0dd3482-f057-44d6-a626-9c9389ad2583","rank":2,"personaId":"b53815ab-d753-4415-9ea6-03a4519c3222","personaName":"Rebellions","avatarUrl":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b.jpg","avatarUrlSmall":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b.jpg","avatarUrlMedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b_medium.jpg","avatarUrlLarge":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b_full.jpg","ladderType":"Ranked","ladderId":"de5bfc9a-9092-4014-b52e-89151de42646","seasonId":"fd7dd807-4ac2-40ec-8476-a4b2937f70af","bracketId":0,"bracketName":"Legendary","rankingScore":38,"secondaryScore":2049,"ruleTypeId":1,"wins":767,"losses":188,"ties":0,"tieStreak":0,"winStreak":3,"lossStreak":0,"longestTieStreak":0,"longestWinStreak":52,"longestLossStreak":6,"bracketMaxScore":0,"bracketScore":0,"updateDate":"2017-10-29T18:03:33.92Z","totalMatchesPlayed":955,"dataInteger":{"totalUnitsKilled ":293274,"totalTitansKilled":88,"totalTimePlayed":924881,"phC-TotalGamesPlayed":4,"substrate-TotalGamesPlayed":350,"lastReplayVersion":250285270,"replayUploadedCount":703}}]
There is a space in your json key name ("totalUnitsKilled ") which is ultimately converted to a variable name.
Correct your JSON key name will fix this issue. There are other keys with error as well.
You can check at http://json2csharp.com/. Wherever it is "invalid_name", key name is wrong.
public class DataInteger
{
public int __invalid_name__totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
public int __invalid_name__substrate-TotalGamesPlayed { get; set; }
public int __invalid_name__phC-TotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}
public class RootObject
{
public string personaLadderId { get; set; }
public int rank { get; set; }
public string personaId { get; set; }
public string personaName { get; set; }
public string avatarUrl { get; set; }
public string avatarUrlSmall { get; set; }
public string avatarUrlMedium { get; set; }
public string avatarUrlLarge { get; set; }
public string ladderType { get; set; }
public string ladderId { get; set; }
public string seasonId { get; set; }
public int bracketId { get; set; }
public string bracketName { get; set; }
public int rankingScore { get; set; }
public int secondaryScore { get; set; }
public int ruleTypeId { get; set; }
public int wins { get; set; }
public int losses { get; set; }
public int ties { get; set; }
public int tieStreak { get; set; }
public int winStreak { get; set; }
public int lossStreak { get; set; }
public int longestTieStreak { get; set; }
public int longestWinStreak { get; set; }
public int longestLossStreak { get; set; }
public int bracketMaxScore { get; set; }
public int bracketScore { get; set; }
public DateTime updateDate { get; set; }
public int totalMatchesPlayed { get; set; }
public DataInteger dataInteger { get; set; }
}
You can use JSON.Net attributes to define C# variables related to JSON key names. Check this for more details.
Your new class should look like:
public class DataInteger
{
[JsonProperty(PropertyName = "totalUnitsKilled ")]
public int totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
[JsonProperty(PropertyName = "substrate-TotalGamesPlayed")]
public int substrateTotalGamesPlayed { get; set; }
[JsonProperty(PropertyName = "phC-TotalGamesPlayed")]
public int phCTotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}

Error during deserialize JSON windows phone 8

I got a api that returns this JSON code:
[{"startDate":1409553000000,
"endDate":1409570100000,
"moduleCode":"#SPLUS0EBB2C",
"activityDescription":"User Interface Design (Tjuna)","staffMembers":[],
"locations":[{"id":"E404A902125255D3330455204193CC29","name":"HAA-H1-21","key":"14124","capacity":24,"url":null,"avoidConcurrencyLocationIds":[]}],
"studentSets":["INF3s","INF4a"],
"activityTypeName":"Other","activityTypeDescription":null,"notes":null,"highlighted":false,
"timetableKeys":["2013!studentsetgroup!9EEA55042B995043A2BC5739BF428E07"]}]
To deserialize I have this code:
var responseObject = await JsonConvert.DeserializeObjectAsync<Apicalls.Rooster>(json);
class Rooster
{
public string startDate { get; set; }
public string endDate { get; set; }
public string activityDescription { get; set; }
public locations[] locations { get; set; }
public string studentSets { get; set; }
}
public class locations
{
public string name { get; set; }
}
Everytime I try to deserialize it gives a error that it's not possible to deserialize the json code. Can anyone help me with this problem?
Rooster
public class Rooster
{
public long startDate { get; set; }
public long endDate { get; set; }
public string moduleCode { get; set; }
public string activityDescription { get; set; }
public List<object> staffMembers { get; set; }
public List<Location> locations { get; set; }
public List<string> studentSets { get; set; }
public string activityTypeName { get; set; }
public object activityTypeDescription { get; set; }
public object notes { get; set; }
public bool highlighted { get; set; }
public List<string> timetableKeys { get; set; }
}
Location
public class Location
{
public string id { get; set; }
public string name { get; set; }
public string key { get; set; }
public int capacity { get; set; }
public object url { get; set; }
public List<object> avoidConcurrencyLocationIds { get; set; }
}
Code:
var responseObject =
await JsonConvert.DeserializeObjectAsync<List<Apicalls.Rooster>>(json);
Demo

Convert Json Http request to c# obj

I`m new in programming winodws 8 app , i have a webservice when i try to connect it using httprequest (Using URL with variables), this service return this:
{"d":"{\"sessionid\":\"twzv50okccwvgggeesjje2wa\",\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":2,\"PriceChangedTimer\":25,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":false,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"VertexFX 10\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1444\",\"Username\":\"test\",\"LastTickTime\":\"\/Date(1396307573431)\/\",\"SelectedAccount\":78821860,\"Name\":0,\"ServicePath\":null,\"GWSessionID\":\"56630\",\"IP\":\"Web (212.35.90.211)\",\"SessionDateStart\":\"01/04/2014 02:12:53\",\"CompanyName\":\"Hybrid Solutions\",\"UserId\":6119,\"DemoClient\":\"0\",\"FName\":\"omqrstu\",\"SName\":\"\",\"TName\":\"\",\"LName\":\"\",\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"2\",\"AlertSms\":\"2\",\"Temp\":null,\"GMTOffset\":\"2\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"1\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Welcome to V 10\",\"DealerTreePriv\":1}"}
i have simple windows app with one button when i click the button i send the url with variables and i got the obj above , i want to use content of this object like UserID in if statement but with no vain i dont know how to use it in C# , can and body help me??
I use this code. I know it has many errors but I need someone guide me.
private void Button_Click(object sender, RoutedEventArgs e)
{
String uriString = "url";
var uri = new Uri(uriString);
var httpWebRequest = HttpWebRequest.Create(uri);
httpWebRequest.BeginGetResponse(new AsyncCallback(OnGettingResponse), httpWebRequest);
}
private void OnGettingResponse(IAsyncResult ar)
{
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );
MessageBox.Show(root.UserId);
}
This is kind of a nasty situation. What you're getting back is a JSON object with a single property (i.e. d) and that property contains a string of JSON. So you basically need to unwrap the inner JSON from it's envelope. The following classes/code should work (using JSON.NET to do the deserialization).
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public int UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );

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