Parsing JSON request - receiving error - c#

I am currently receiving JSON and I'm trying to then get that response broken down and into a class. The code I have so far is as follows:
public class Response
{
public string ID { get; set; }
public string Description { get; set; }
}
public void Example()
{
string JSONResponse = JsonConvert.SerializeObject(FetchDeskData("cases"));
// Errors on this next line
Response trimmedResponse = JsonConvert.DeserializeObject<Response>(JSONResponse);
}
The data that "FetchDeskData("cases") is returning is (this), however, on the line that errors, I receive the following error:
Error converting value "{"total_entries":598042,"page":1,"...(continues)
Should I be parsing this JSON in a different way? Is there something I should be doing prior to serialising/deserialising?
I'm pulling this data from desk.com, they have some documentation that you can find at http://dev.desk.com but it doesn't seem to be telling me that I need to filter something out before parsing it.
Any help is appreciated, thank you.

You can use Visual Studio 2013, 2015 to create your model classes from a json, I did it and I parsed the JSON fine.
To use this feature, you must have JSON/XML in your clipboard, put your cursor inside a .cs file and then use the option Edit > Paste Special > Paste JSON AS Classes
Look the code that was generated:
class Program
{
static void Main(string[] args)
{
var str = #"{
""total_entries"": 598042,
""page"": 1,
""_links"": {
""self"": {
""href"": ""\/api\/v2\/cases?page=1&per_page=50"",
""class"": ""page""
},
""first"": {
""href"": ""\/api\/v2\/cases?page=1&per_page=50"",
""class"": ""page""
},
""last"": {
""href"": ""\/api\/v2\/cases?page=11961&per_page=50"",
""class"": ""page""
},
""previous"": null,
""next"": {
""href"": ""\/api\/v2\/cases?page=2&per_page=50"",
""class"": ""page""
}
},
""_embedded"": {
""entries"": [
{
""id"": 1,
""external_id"": null,
""blurb"": ""I want to personally thank you for signing up to try Desk.com! To ensure you get the most out of your trial,
here are some helpful tips and quick ways to get started: \\n\\n1. USE IT - You\\u2019ve got 14 days to try us out - please do so and tell us what you t"",
""priority"": 4,
""locked_until"": null,
""label_ids"": [
],
""active_at"": ""2015-01-21T15: 10: 48Z"",
""changed_at"": ""2015-01-21T15: 15: 44Z"",
""created_at"": ""2015-01-20T16: 24: 09Z"",
""updated_at"": ""2015-01-21T15: 15: 44Z"",
""first_opened_at"": ""2015-01-21T15: 10: 47Z"",
""opened_at"": ""2015-01-21T15: 10: 47Z"",
""first_resolved_at"": ""2015-01-21T15: 15: 44Z"",
""resolved_at"": ""2015-01-21T15: 15: 44Z"",
""status"": ""resolved"",
""active_notes_count"": 0,
""active_attachments_count"": 0,
""has_pending_interactions"": false,
""has_failed_interactions"": false,
""description"": null,
""language"": null,
""received_at"": ""2015-01-20T16: 24: 09Z"",
""type"": ""email"",
""labels"": [
],
""subject"": ""Getting Started with Your New Account"",
""route_status"": ""available"",
""custom_fields"": {
""exclude_portal"": null,
""exclude_notifications"": null,
""case_type"": null,
""product"": null,
""severity"": null,
""knowledge_status"": null,
""desk_case_id"": null,
""sla_status"": null,
""priority"": null,
""sla_violation"": null,
""sla_milestone_completed"": null,
""sync_to_salesforce"": null,
""7616_pa2"": null,
""7643_pa1"": null,
""7714_pa1"": null,
""7616_pa1"": null,
""7643_pa2"": null,
""7714_pa2"": null,
""entitlement_name"": null,
""escalation_level"": null,
""testing"": null,
""defect_number"": null,
""channel"": null,
""product_version"": null,
""exclude_from_reporting"": null,
""cw_id"": null,
""desk_agent_id"": null,
""desk_agent_name"": null,
""solution_codes"": null,
""7723_pa2"": null,
""7670_pa2"": null,
""7661_pa1"": null,
""7634_pa2"": null,
""7670_pa1"": null,
""7758_pa1"": null,
""7634_pa1"": null,
""7688_pa1"": null,
""7723_pa1"": null,
""7688_pa2"": null,
""7661_pa2"": null,
""7758_pa2"": null,
""7697_pa1"": null,
""problem_area_1"": null,
""problem_area_2"": null,
""spam"": null,
""salesforce_problem_area_1"": null,
""salesforce_problem_area_2"": null,
""brand_id"": null
},
""_links"": {
""self"": {
""href"": ""\/api\/v2\/cases\/1"",
""class"": ""case""
},
""message"": {
""href"": ""\/api\/v2\/cases\/1\/message"",
""class"": ""email""
},
""customer"": {
""href"": ""\/api\/v2\/customers\/287193532"",
""class"": ""customer""
},
""labels"": {
""href"": ""\/api\/v2\/cases\/1\/labels"",
""class"": ""label""
},
""assigned_user"": {
""href"": ""\/api\/v2\/users\/22787152"",
""class"": ""user""
},
""assigned_group"": {
""href"": ""\/api\/v2\/groups\/474802"",
""class"": ""group""
},
""locked_by"": null,
""history"": {
""href"": ""\/api\/v2\/cases\/1\/history"",
""class"": ""history""
},
""case_links"": {
""href"": ""\/api\/v2\/cases\/1\/links"",
""class"": ""case_link"",
""count"": 0
},
""macro_preview"": {
""href"": ""\/api\/v2\/cases\/1\/macros\/preview"",
""class"": ""macro_preview""
},
""replies"": {
""href"": ""\/api\/v2\/cases\/1\/replies"",
""class"": ""reply"",
""count"": 1
},
""draft"": {
""href"": ""\/api\/v2\/cases\/1\/replies\/draft"",
""class"": ""reply""
},
""notes"": {
""href"": ""\/api\/v2\/cases\/1\/notes"",
""class"": ""note"",
""count"": 0
},
""attachments"": {
""href"": ""\/api\/v2\/cases\/1\/attachments"",
""class"": ""attachment"",
""count"": 0
}
}
}
]
}
}";
var deserializeObject = JsonConvert.DeserializeObject<Rootobject>(str);
Console.WriteLine(deserializeObject.total_entries);
}
}
public class Rootobject
{
public int total_entries { get; set; }
public int page { get; set; }
public _Links _links { get; set; }
public _Embedded _embedded { get; set; }
}
public class _Links
{
public Self self { get; set; }
public First first { get; set; }
public Last last { get; set; }
public object previous { get; set; }
public Next next { get; set; }
}
public class Self
{
public string href { get; set; }
public string _class { get; set; }
}
public class First
{
public string href { get; set; }
public string _class { get; set; }
}
public class Last
{
public string href { get; set; }
public string _class { get; set; }
}
public class Next
{
public string href { get; set; }
public string _class { get; set; }
}
public class _Embedded
{
public Entry[] entries { get; set; }
}
public class Entry
{
public int id { get; set; }
public object external_id { get; set; }
public string blurb { get; set; }
public int priority { get; set; }
public object locked_until { get; set; }
public object[] label_ids { get; set; }
public string active_at { get; set; }
public string changed_at { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string first_opened_at { get; set; }
public string opened_at { get; set; }
public string first_resolved_at { get; set; }
public string resolved_at { get; set; }
public string status { get; set; }
public int active_notes_count { get; set; }
public int active_attachments_count { get; set; }
public bool has_pending_interactions { get; set; }
public bool has_failed_interactions { get; set; }
public object description { get; set; }
public object language { get; set; }
public string received_at { get; set; }
public string type { get; set; }
public object[] labels { get; set; }
public string subject { get; set; }
public string route_status { get; set; }
public Custom_Fields custom_fields { get; set; }
public _Links1 _links { get; set; }
}
public class Custom_Fields
{
public object exclude_portal { get; set; }
public object exclude_notifications { get; set; }
public object case_type { get; set; }
public object product { get; set; }
public object severity { get; set; }
public object knowledge_status { get; set; }
public object desk_case_id { get; set; }
public object sla_status { get; set; }
public object priority { get; set; }
public object sla_violation { get; set; }
public object sla_milestone_completed { get; set; }
public object sync_to_salesforce { get; set; }
public object _7616_pa2 { get; set; }
public object _7643_pa1 { get; set; }
public object _7714_pa1 { get; set; }
public object _7616_pa1 { get; set; }
public object _7643_pa2 { get; set; }
public object _7714_pa2 { get; set; }
public object entitlement_name { get; set; }
public object escalation_level { get; set; }
public object testing { get; set; }
public object defect_number { get; set; }
public object channel { get; set; }
public object product_version { get; set; }
public object exclude_from_reporting { get; set; }
public object cw_id { get; set; }
public object desk_agent_id { get; set; }
public object desk_agent_name { get; set; }
public object solution_codes { get; set; }
public object _7723_pa2 { get; set; }
public object _7670_pa2 { get; set; }
public object _7661_pa1 { get; set; }
public object _7634_pa2 { get; set; }
public object _7670_pa1 { get; set; }
public object _7758_pa1 { get; set; }
public object _7634_pa1 { get; set; }
public object _7688_pa1 { get; set; }
public object _7723_pa1 { get; set; }
public object _7688_pa2 { get; set; }
public object _7661_pa2 { get; set; }
public object _7758_pa2 { get; set; }
public object _7697_pa1 { get; set; }
public object problem_area_1 { get; set; }
public object problem_area_2 { get; set; }
public object spam { get; set; }
public object salesforce_problem_area_1 { get; set; }
public object salesforce_problem_area_2 { get; set; }
public object brand_id { get; set; }
}
public class _Links1
{
public Self1 self { get; set; }
public Message message { get; set; }
public Customer customer { get; set; }
public Labels labels { get; set; }
public Assigned_User assigned_user { get; set; }
public Assigned_Group assigned_group { get; set; }
public object locked_by { get; set; }
public History history { get; set; }
public Case_Links case_links { get; set; }
public Macro_Preview macro_preview { get; set; }
public Replies replies { get; set; }
public Draft draft { get; set; }
public Notes notes { get; set; }
public Attachments attachments { get; set; }
}
public class Self1
{
public string href { get; set; }
public string _class { get; set; }
}
public class Message
{
public string href { get; set; }
public string _class { get; set; }
}
public class Customer
{
public string href { get; set; }
public string _class { get; set; }
}
public class Labels
{
public string href { get; set; }
public string _class { get; set; }
}
public class Assigned_User
{
public string href { get; set; }
public string _class { get; set; }
}
public class Assigned_Group
{
public string href { get; set; }
public string _class { get; set; }
}
public class History
{
public string href { get; set; }
public string _class { get; set; }
}
public class Case_Links
{
public string href { get; set; }
public string _class { get; set; }
public int count { get; set; }
}
public class Macro_Preview
{
public string href { get; set; }
public string _class { get; set; }
}
public class Replies
{
public string href { get; set; }
public string _class { get; set; }
public int count { get; set; }
}
public class Draft
{
public string href { get; set; }
public string _class { get; set; }
}
public class Notes
{
public string href { get; set; }
public string _class { get; set; }
public int count { get; set; }
}
public class Attachments
{
public string href { get; set; }
public string _class { get; set; }
public int count { get; set; }
}

I solved this by using the following code in order to parse/read the response from the API:
private void TestProcess()
{
JObject objData = JObject.Parse(FetchJSONData());
string sName = (string)objData["customers"][1]["Name"];
int iAge = (int)objData["customers"][1]["Age"];
}
private string FetchJSONData()
{
WebRequest req = WebRequest.Create("https://api.website.com");
string sAPICredentials = "username" + ":" + "password";
req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(sAPICredentials)));
try
{
WebResponse res = req.GetResponse();
Stream rcvStream = res.GetResponseStream();
StreamReader rdrStream = new StreamReader(rcvStream, Encoding.UTF8);
string JSONResponse = rdrStream.ReadToEnd();
return JSONResponse;
}
catch (WebException we)
{
var response = we.Response as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.Forbidden)
{
// Deal with error
}
}
}
This is a simplified example and you should be populating a class with this information, however this should get you started in retrieving the data.

Related

Value from deserialized JSON object is NULL

I am having some trouble getting a value from a deserialized JSON string.
Here is my JSON string:
{
"expand": "names,schema",
"startAt": 0,
"maxResults": 1,
"total": 151,
"issues": [
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id": "10210",
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issue/10210",
"key": "ITSD-202",
"fields": {
"statuscategorychangedate": "2021-01-25T20:12:11.922+0000",
"issuetype": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issuetype/10003",
"id": "10003",
"description": "For customer support issues. Created by Jira Service Desk.",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/secure/viewavatar?size=medium&avatarId=10308&avatarType=issuetype",
"name": "Support",
"subtask": false,
"avatarId": 10308
},
"timespent": null,
"customfield_10030": null,
"customfield_10031": {
"id": "1",
"name": "Time to resolution",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/request/10210/sla/1"
},
"completedCycles": [],
"ongoingCycle": {
"startTime": {
"iso8601": "2021-01-25T20:12:11+0000",
"jira": "2021-01-25T20:12:11.592+0000",
"friendly": "Yesterday 08:12",
"epochMillis": 1611605531592
},
"breachTime": {
"iso8601": "2021-02-11T14:30:00+0000",
"jira": "2021-02-11T14:30:00.000+0000",
"friendly": "11/Feb/21 02:30",
"epochMillis": 1613053800000
},
"breached": false,
"paused": false,
"withinCalendarHours": false,
"goalDuration": {
"millis": 432000000,
"friendly": "120h"
},
"elapsedTime": {
"millis": 0,
"friendly": "0m"
},
"remainingTime": {
"millis": 432000000,
"friendly": "120h"
}
}
},
"project": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/project/10000",
"id": "10000",
"key": "ITSD",
"name": "Customer Service Desk",
"projectTypeKey": "service_desk",
"simplified": false,
"avatarUrls": {
"48x48": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?pid=10000&avatarId=10412",
"24x24": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=small&s=small&pid=10000&avatarId=10412",
"16x16": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=xsmall&s=xsmall&pid=10000&avatarId=10412",
"32x32": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=medium&s=medium&pid=10000&avatarId=10412"
}
},
"customfield_10032": {
"id": "2",
"name": "Time to first response",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/request/10210/sla/2"
},
"completedCycles": [],
"ongoingCycle": {
"startTime": {
"iso8601": "2021-01-25T20:12:11+0000",
"jira": "2021-01-25T20:12:11.592+0000",
"friendly": "Yesterday 08:12",
"epochMillis": 1611605531592
},
"breachTime": {
"iso8601": "2021-01-26T12:30:00+0000",
"jira": "2021-01-26T12:30:00.000+0000",
"friendly": "Today 12:30",
"epochMillis": 1611664200000
},
"breached": false,
"paused": false,
"withinCalendarHours": false,
"goalDuration": {
"millis": 14400000,
"friendly": "4h"
},
"elapsedTime": {
"millis": 0,
"friendly": "0m"
},
"remainingTime": {
"millis": 14400000,
"friendly": "4h"
}
}
},
"fixVersions": [],
"customfield_10034": {
"languageCode": "en",
"displayName": "English"
},
"resolution": null,
"customfield_10037": null,
"customfield_10027": null,
"customfield_10028": null,
"customfield_10029": null,
"resolutiondate": null,
"workratio": -1,
"lastViewed": "2021-01-25T20:12:11.936+0000",
"watches": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issue/ITSD-202/watchers",
"watchCount": 1,
"isWatching": true
},
"created": "2021-01-25T20:12:11.592+0000",
"customfield_10020": null,
"customfield_10021": null,
"customfield_10022": null,
"customfield_10023": null,
"priority": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/priority/3",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/images/icons/priorities/medium.svg",
"name": "Medium",
"id": "3"
},
"customfield_10024": null,
"customfield_10025": null,
"labels": [],
"customfield_10026": [],
"customfield_10016": null,
"customfield_10017": null,
"customfield_10018": {
"hasEpicLinkFieldDependency": false,
"showField": false,
"nonEditableReason": {
"reason": "PLUGIN_LICENSE_ERROR",
"message": "The Parent Link is only available to Jira Premium users."
}
},
"customfield_10019": "0|i0013b:",
"timeestimate": null,
"versions": [],
"assignee": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"updated": "2021-01-25T20:12:14.321+0000",
"status": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/status/10001",
"description": "This was auto-generated by Jira Service Desk during workflow import",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/images/icons/status_generic.gif",
"name": "Waiting for support",
"id": "10001",
"statusCategory": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/statuscategory/4",
"id": 4,
"key": "indeterminate",
"colorName": "yellow",
"name": "In Progress"
}
},
"components": [],
"customfield_10050": null,
"customfield_10051": null,
"timeoriginalestimate": null,
"customfield_10052": null,
"customfield_10053": null,
"description": null,
"customfield_10010": null,
"customfield_10014": null,
"customfield_10015": null,
"customfield_10005": null,
"customfield_10049": null,
"customfield_10006": null,
"customfield_10007": null,
"security": null,
"customfield_10008": null,
"customfield_10009": null,
"summary": "Barry Test",
"creator": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"customfield_10040": null,
"customfield_10041": null,
"customfield_10042": null,
"customfield_10043": null,
"reporter": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"customfield_10044": null,
"customfield_10000": "{}",
"customfield_10001": null,
"customfield_10045": null,
"customfield_10046": null,
"customfield_10002": [
{
"id": "4",
"name": "xxxxxxxxxx.co.uk",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/organization/4"
}
}
],
"customfield_10003": null,
"customfield_10047": null,
"customfield_10048": null,
"customfield_10004": null,
"customfield_10038": null,
"customfield_10039": null,
"environment": null,
"duedate": null,
"progress": {
"progress": 0,
"total": 0
}
}
}
]
}
And this is how I am deseriazling it and trying to return the values.
var root = JsonConvert.DeserializeObject<Rootobject2>(response.Content);
foreach (var issue in root.issues)
{
string id = issue.id.ToString();
string key = issue.key.ToString();
string summary = issue.fields.summary.ToString();
string creatoremail = issue.fields.creator.emailAddress.ToString();
public class Rootobject2
{
public string expand { get; set; }
public int startAt { get; set; }
public int maxResults { get; set; }
public int total { get; set; }
public Issue[] issues { get; set; }
}
public class Issue
{
public string expand { get; set; }
public string id { get; set; }
public string self { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Fields
{
public DateTime statuscategorychangedate { get; set; }
public Issuetype issuetype { get; set; }
public int? timespent { get; set; }
public object customfield_10030 { get; set; }
public Customfield_10031 customfield_10031 { get; set; }
public Project project { get; set; }
public Customfield_10032 customfield_10032 { get; set; }
public object[] fixVersions { get; set; }
public Customfield_10034 customfield_10034 { get; set; }
public Resolution resolution { get; set; }
public object customfield_10037 { get; set; }
public object customfield_10027 { get; set; }
public object customfield_10028 { get; set; }
public object customfield_10029 { get; set; }
public DateTime? resolutiondate { get; set; }
public int workratio { get; set; }
public DateTime? lastViewed { get; set; }
public Watches watches { get; set; }
public DateTime created { get; set; }
public object customfield_10020 { get; set; }
public object customfield_10021 { get; set; }
public object customfield_10022 { get; set; }
public Priority priority { get; set; }
public object customfield_10023 { get; set; }
public DateTime? customfield_10024 { get; set; }
public string customfield_10025 { get; set; }
public object[] customfield_10026 { get; set; }
public object[] labels { get; set; }
public object customfield_10016 { get; set; }
public object customfield_10017 { get; set; }
public Customfield_10018 customfield_10018 { get; set; }
public string customfield_10019 { get; set; }
public int? timeestimate { get; set; }
public object[] versions { get; set; }
public Assignee assignee { get; set; }
public DateTime updated { get; set; }
public Status status { get; set; }
public Component[] components { get; set; }
public object customfield_10050 { get; set; }
public object customfield_10051 { get; set; }
public object timeoriginalestimate { get; set; }
public object customfield_10052 { get; set; }
public object customfield_10053 { get; set; }
public Description description { get; set; }
public Customfield_10010 customfield_10010 { get; set; }
public object customfield_10014 { get; set; }
public object customfield_10015 { get; set; }
public object customfield_10005 { get; set; }
public object customfield_10049 { get; set; }
public object customfield_10006 { get; set; }
public object customfield_10007 { get; set; }
public object security { get; set; }
public object customfield_10008 { get; set; }
public object customfield_10009 { get; set; }
public string summary { get; set; }
public Creator creator { get; set; }
public object customfield_10040 { get; set; }
public object customfield_10041 { get; set; }
public object customfield_10042 { get; set; }
public object customfield_10043 { get; set; }
public Reporter reporter { get; set; }
public string customfield_10000 { get; set; }
public object customfield_10044 { get; set; }
public object customfield_10045 { get; set; }
public object customfield_10001 { get; set; }
public object customfield_10046 { get; set; }
public Customfield_10002[] customfield_10002 { get; set; }
public object customfield_10047 { get; set; }
public object customfield_10003 { get; set; }
public object customfield_10048 { get; set; }
public object customfield_10004 { get; set; }
public object customfield_10038 { get; set; }
public object customfield_10039 { get; set; }
public object environment { get; set; }
public object duedate { get; set; }
public Progress progress { get; set; }
}
(Dictionary created by doing paste special values in Visual Studio)
The issue I am seeing, I get "Object reference not set to an instance of an object." on
foreach (var issue in root.issues)
Any help greatly appreciated
Your class for deserialization should look something like this
public class Issuetype {
public string self { get; set; }
public string id { get; set; }
public string description { get; set; }
public string iconUrl { get; set; }
public string name { get; set; }
public bool subtask { get; set; }
public int avatarId { get; set; }
}
public class Links {
public string self { get; set; }
}
public class StartTime {
public DateTime iso8601 { get; set; }
public DateTime jira { get; set; }
public string friendly { get; set; }
public long epochMillis { get; set; }
}
public class BreachTime {
public DateTime iso8601 { get; set; }
public DateTime jira { get; set; }
public string friendly { get; set; }
public long epochMillis { get; set; }
}
public class GoalDuration {
public int millis { get; set; }
public string friendly { get; set; }
}
public class ElapsedTime {
public int millis { get; set; }
public string friendly { get; set; }
}
public class RemainingTime {
public int millis { get; set; }
public string friendly { get; set; }
}
public class OngoingCycle {
public StartTime startTime { get; set; }
public BreachTime breachTime { get; set; }
public bool breached { get; set; }
public bool paused { get; set; }
public bool withinCalendarHours { get; set; }
public GoalDuration goalDuration { get; set; }
public ElapsedTime elapsedTime { get; set; }
public RemainingTime remainingTime { get; set; }
}
public class Customfield10031 {
public string id { get; set; }
public string name { get; set; }
public Links _links { get; set; }
public List<object> completedCycles { get; set; }
public OngoingCycle ongoingCycle { get; set; }
}
public class AvatarUrls {
public string _48x48 { get; set; }
public string _24x24 { get; set; }
public string _16x16 { get; set; }
public string _32x32 { get; set; }
}
public class Project {
public string self { get; set; }
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string projectTypeKey { get; set; }
public bool simplified { get; set; }
public AvatarUrls avatarUrls { get; set; }
}
public class Customfield10032 {
public string id { get; set; }
public string name { get; set; }
public Links _links { get; set; }
public List<object> completedCycles { get; set; }
public OngoingCycle ongoingCycle { get; set; }
}
public class Customfield10034 {
public string languageCode { get; set; }
public string displayName { get; set; }
}
public class Watches {
public string self { get; set; }
public int watchCount { get; set; }
public bool isWatching { get; set; }
}
public class Priority {
public string self { get; set; }
public string iconUrl { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class NonEditableReason {
public string reason { get; set; }
public string message { get; set; }
}
public class Customfield10018 {
public bool hasEpicLinkFieldDependency { get; set; }
public bool showField { get; set; }
public NonEditableReason nonEditableReason { get; set; }
}
public class Assignee {
public string self { get; set; }
public string accountId { get; set; }
public string emailAddress { get; set; }
public AvatarUrls avatarUrls { get; set; }
public string displayName { get; set; }
public bool active { get; set; }
public string timeZone { get; set; }
public string accountType { get; set; }
}
public class StatusCategory {
public string self { get; set; }
public int id { get; set; }
public string key { get; set; }
public string colorName { get; set; }
public string name { get; set; }
}
public class Status {
public string self { get; set; }
public string description { get; set; }
public string iconUrl { get; set; }
public string name { get; set; }
public string id { get; set; }
public StatusCategory statusCategory { get; set; }
}
public class Creator {
public string self { get; set; }
public string accountId { get; set; }
public string emailAddress { get; set; }
public AvatarUrls avatarUrls { get; set; }
public string displayName { get; set; }
public bool active { get; set; }
public string timeZone { get; set; }
public string accountType { get; set; }
}
public class Reporter {
public string self { get; set; }
public string accountId { get; set; }
public string emailAddress { get; set; }
public AvatarUrls avatarUrls { get; set; }
public string displayName { get; set; }
public bool active { get; set; }
public string timeZone { get; set; }
public string accountType { get; set; }
}
public class Customfield10002 {
public string id { get; set; }
public string name { get; set; }
public Links _links { get; set; }
}
public class Progress {
public int progress { get; set; }
public int total { get; set; }
}
public class Fields {
public DateTime statuscategorychangedate { get; set; }
public Issuetype issuetype { get; set; }
public object timespent { get; set; }
public object customfield_10030 { get; set; }
public Customfield10031 customfield_10031 { get; set; }
public Project project { get; set; }
public Customfield10032 customfield_10032 { get; set; }
public List<object> fixVersions { get; set; }
public Customfield10034 customfield_10034 { get; set; }
public object resolution { get; set; }
public object customfield_10037 { get; set; }
public object customfield_10027 { get; set; }
public object customfield_10028 { get; set; }
public object customfield_10029 { get; set; }
public object resolutiondate { get; set; }
public int workratio { get; set; }
public DateTime lastViewed { get; set; }
public Watches watches { get; set; }
public DateTime created { get; set; }
public object customfield_10020 { get; set; }
public object customfield_10021 { get; set; }
public object customfield_10022 { get; set; }
public object customfield_10023 { get; set; }
public Priority priority { get; set; }
public object customfield_10024 { get; set; }
public object customfield_10025 { get; set; }
public List<object> labels { get; set; }
public List<object> customfield_10026 { get; set; }
public object customfield_10016 { get; set; }
public object customfield_10017 { get; set; }
public Customfield10018 customfield_10018 { get; set; }
public string customfield_10019 { get; set; }
public object timeestimate { get; set; }
public List<object> versions { get; set; }
public Assignee assignee { get; set; }
public DateTime updated { get; set; }
public Status status { get; set; }
public List<object> components { get; set; }
public object customfield_10050 { get; set; }
public object customfield_10051 { get; set; }
public object timeoriginalestimate { get; set; }
public object customfield_10052 { get; set; }
public object customfield_10053 { get; set; }
public object description { get; set; }
public object customfield_10010 { get; set; }
public object customfield_10014 { get; set; }
public object customfield_10015 { get; set; }
public object customfield_10005 { get; set; }
public object customfield_10049 { get; set; }
public object customfield_10006 { get; set; }
public object customfield_10007 { get; set; }
public object security { get; set; }
public object customfield_10008 { get; set; }
public object customfield_10009 { get; set; }
public string summary { get; set; }
public Creator creator { get; set; }
public object customfield_10040 { get; set; }
public object customfield_10041 { get; set; }
public object customfield_10042 { get; set; }
public object customfield_10043 { get; set; }
public Reporter reporter { get; set; }
public object customfield_10044 { get; set; }
public string customfield_10000 { get; set; }
public object customfield_10001 { get; set; }
public object customfield_10045 { get; set; }
public object customfield_10046 { get; set; }
public List<Customfield10002> customfield_10002 { get; set; }
public object customfield_10003 { get; set; }
public object customfield_10047 { get; set; }
public object customfield_10048 { get; set; }
public object customfield_10004 { get; set; }
public object customfield_10038 { get; set; }
public object customfield_10039 { get; set; }
public object environment { get; set; }
public object duedate { get; set; }
public Progress progress { get; set; }
}
public class Issue {
public string expand { get; set; }
public string id { get; set; }
public string self { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Root {
public string expand { get; set; }
public int startAt { get; set; }
public int maxResults { get; set; }
public int total { get; set; }
public List<Issue> issues { get; set; }
}
and you'd deserialize like this
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
Always try to see references when creting json objects, I use this page
As commmented below, this would be the main:
using Newtonsoft.Json;
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Root myDeserializedClass = JsonConvert.DeserializeObject<Root> (File.ReadAllText(#"response.json"));
foreach (var issue in myDeserializedClass.issues)
{
string id = issue.id.ToString();
string key = issue.key.ToString();
string summary = issue.fields.summary.ToString();
string creatoremail = issue.fields.creator.emailAddress.ToString();
}
}
}
}
I think the problem you're having might be the way you're writting your foreach? I mean the code seems to be lacking something, but perhaps you shortened it.

JsonConvert.DeserializeObject throws Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.3.0.0, Cultur

string jsonDoc = #"{
""pricingDetails"": [{
""pricingStrategyId"": 1,
""pricingStrategy"": {
""id"": 1,
""name"": ""PREPAY_FIXED"",
""displayText"": ""Prepay fixed"",
""description"": ""Pay onsite a fixed price at entry.""
},
""siteId"": 262,
""site"": {
""id"": 262,
""buildingId"": 64,
""siteName"": ""Test Site"",
""siteDescription"": ""test1"",
""isListed"": null,
""listedDateTime"": null,
""siteAfterHoursInstructions"": null,
""archiveDateTime"": null,
""archivedBy"": null,
""createdDateTime"": ""2019-04-09T00:00:00"",
""modifyDateTime"": ""2019-04-09T14:59:54.87"",
""statusId"": 5,
""siteMaxHeight"": ""2.1"",
""businessRegistrationId"": ""2019-105A110BU69L64B262"",
""businessAbnOracnNumber"": ""48 110 366 946"",
""businessPhoneNumber"": ""02 9017 1292"",
""businessFaxNumber"": """",
""bankAccountName"": null,
""bankAccountNumber"": null,
""bankBsbnumber"": null,
""bankEmailAddresses"": null,
""physicalAddressLine2"": """",
""physicalAddressSuburb"": ""Sydney"",
""physicalAddressState"": ""NSW"",
""physicalAddressPostcode"": 2000,
""postalAddressLine2"": """",
""postalAddressSuburb"": ""Sydney"",
""postalAddressState"": ""NSW"",
""postalAddressPostcode"": 2000,
""entryAddressLine2"": null,
""exitAddressLine2"": null,
""bankReferenceNo"": null,
""isGstregistered"": null,
""refParentBankDets"": false,
""canTakePayments"": false,
""siteOpenTime"": 60,
""siteCloseTime"": 1260,
""siteAccessOpenTime"": 360,
""siteAccessCloseTime"": 1080,
""occupiedTypeId"": 2,
""siteNotes"": null,
""securityType"": true,
""keyDelivery"": 3,
""keyInstrPickup"": null,
""keyInstrReturn"": null,
""smartCmsgLine1"": null,
""smartCmsgLine2"": null,
""instrGracePeriod"": null,
""instrOverstay"": null,
""isUnusedBay"": false,
""navStatusId"": 0,
""navErrorMsg"": null,
""priorityPass"": null,
""siteCommision"": 0,
""entryGracePeriod"": null,
""exitGracePeriod"": null,
""bookableDays"": null,
""checkQuota"": null,
""totalSpaces"": null
},
""days"": 31,
""entryTimeOffset"": 360,
""exitTimeOffset"": 1080,
""price"": 7.00
}
],
""relatedDevices"": [{
""id"": 15,
""siteId"": 262,
""roleId"": 2,
""role"": {
""id"": 2,
""name"": ""SC"",
""description"": ""Display device""
},
""sideId"": 1,
""side"": {
""id"": 1,
""name"": ""IN""
},
""lane"": 1,
""deviceGroup"": ""Live""
}, {
""id"": 17,
""siteId"": 262,
""uid"": ""synorb1-exit1-ptg"",
""roleId"": 4,
""role"": {
""id"": 4,
""name"": ""PTG"",
""description"": ""Payment device""
},
""sideId"": 1,
""side"": {
""id"": 1,
""name"": ""IN""
},
""lane"": 1,
""deviceGroup"": ""Live""
}
]
}
"
var obj = JsonConvert.DeserializeObject<ParkingOfferDetailsDTO>(jsonDoc);
==================================
public class ParkingOfferDetailsDTO
{
public List<CasualParkingPricingDetailsVM> PricingDetails { get; set; }
public List<AccessDeviceVM> RelatedDevices { get; set; }
}
public class CasualParkingPricingDetailsVM
{
public int PricingStrategyId { get; set; }
public virtual CasualParkingPricingStrategyVM PricingStrategy { get; set; }
public int SiteId { get; set; }
public virtual SitesVM Site { get; set; }
// Enum.Days |
public int Days { get; set; }
public int? EntryTimeOffset { get; set; }
public int? ExitTimeOffset { get; set; }
public decimal Price { get; set; }
}
public class CasualParkingPricingStrategyVM
{
public int Id { get; set; }
public string Name { get; set; }
public string DisplayText { get; set; }
public string Description { get; set; }
}
public class SitesVM
{
public SitesVM()
{
//Bookings = new HashSet<Bookings>();
//InventoryEntityRelationship = new HashSet<InventoryEntityRelationship>();
//ParkingTypes = new HashSet<ParkingTypes>();
//SiteLicenses = new HashSet<SiteLicenses>();
//SiteTimeZones = new HashSet<SiteTimeZonesVM>();
//Spaces = new HashSet<Spaces>();
}
public int Id { get; set; }
public int BuildingId { get; set; }
public string SiteName { get; set; }
//public string Photos { get; set; }
//public bool? HasOnSiteStaff { get; set; }
//public string OnSiteStaffNotes { get; set; }
public string SiteDescription { get; set; }
public bool? IsListed { get; set; }
public DateTime? ListedDateTime { get; set; }
public string SiteAfterHoursInstructions { get; set; }
public DateTime? ArchiveDateTime { get; set; }
public string ArchivedBy { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDateTime { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifyDateTime { get; set; }
public int StatusId { get; set; }
public string SiteMaxHeight { get; set; }
public string BusinessName { get; set; }
public string BusinessRegistrationId { get; set; }
public string BusinessAbnOracnNumber { get; set; }
public string BusinessPhoneNumber { get; set; }
public string BusinessEmail { get; set; }
public string BusinessFaxNumber { get; set; }
public string BankAccountName { get; set; }
public string BankAccountNumber { get; set; }
public string BankBsbnumber { get; set; }
public string BankEmailAddresses { get; set; }
public string PhysicalAddressLine1 { get; set; }
public string PhysicalAddressLine2 { get; set; }
public string PhysicalAddressSuburb { get; set; }
public string PhysicalAddressState { get; set; }
public int PhysicalAddressPostcode { get; set; }
public string PostalAddressLine1 { get; set; }
public string PostalAddressLine2 { get; set; }
public string PostalAddressSuburb { get; set; }
public string PostalAddressState { get; set; }
public int? PostalAddressPostcode { get; set; }
public string EntryAddressLine2 { get; set; }
public string ExitAddressLine2 { get; set; }
public string BankReferenceNo { get; set; }
public bool? IsGstregistered { get; set; }
public bool RefParentBankDets { get; set; }
public bool CanTakePayments { get; set; }
public short? SiteOpenTime { get; set; }
public short? SiteCloseTime { get; set; }
public short? SiteAccessOpenTime { get; set; }
public short? SiteAccessCloseTime { get; set; }
public int OccupiedTypeId { get; set; }
public string SiteNotes { get; set; }
public bool SecurityType { get; set; }
public int? KeyDelivery { get; set; }
public string KeyInstrPickup { get; set; }
public string KeyInstrReturn { get; set; }
public string SmartCmsgLine1 { get; set; }
public string SmartCmsgLine2 { get; set; }
public string InstrGracePeriod { get; set; }
public string InstrOverstay { get; set; }
public bool IsUnusedBay { get; set; }
public byte NavStatusId { get; set; }
public string NavErrorMsg { get; set; }
public string EntryAddressLine1 { get; set; }
public string EntryAddressSuburb { get; set; }
public string EntryAddressState { get; set; }
public int? EntryAddressPostcode { get; set; }
public string ExitAddressLine1 { get; set; }
public string ExitAddressSuburb { get; set; }
public string ExitAddressState { get; set; }
public int? ExitAddressPostcode { get; set; }
public bool? IsPublicSearchable { get; set; }
public string PriorityPass { get; set; }
public float SiteCommision { get; set; }
public short? EntryGracePeriod { get; set; }
public short? ExitGracePeriod { get; set; }
public int? BookableDays { get; set; }
public bool? CheckQuota { get; set; }
public int? TotalSpaces { get; set; }
//public virtual Buildings Building { get; set; }
//public virtual RefNavStatus NavStatus { get; set; }
//public virtual RefStatus Status { get; set; }
//public virtual ICollection<Bookings> Bookings { get; set; }
//public virtual ICollection<InventoryEntityRelationship> InventoryEntityRelationship { get; set; }
//public virtual ICollection<ParkingTypes> ParkingTypes { get; set; }
//public virtual ICollection<SiteLicenses> SiteLicenses { get; set; }
//public virtual ICollection<SiteTimeZonesVM> SiteTimeZones { get; set; }
//public virtual ICollection<Spaces> Spaces { get; set; }
}
public class AccessDeviceVM
{
public int Id { get; set; }
[Required]
public int SiteId { get; set; }
[Required]
public string UID { get; set; }
[Required]
public int RoleId { get; set; }
public AccessDeviceRoleVM Role { get; set; }
[Required]
public int SideId { get; set; }
public AccessDeviceSideVM Side { get; set; }
[Required]
public int Lane { get; set; }
[Required]
public string DeviceGroup { get; set; }
}
public class AccessDeviceRoleVM
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class AccessDeviceSideVM
{
public int Id { get; set; }
public string Name { get; set; }
}
================
I am tring to deserialize a JSON string in to a nested object. However, it results in an exception. To me the exception looks irrelevant.
Above I have shared the JSON and the C# Class structure. I am trying to Deserialize the JSON but it
throws "Could not load file or assembly 'System.ComponentModel.Annotations, exception...."
I have also tried using a simple object structure and JSON, it worked.
So, as mentioned before, the exception is irrelevant (not helpful). Here is how I debug this issue.
1) Add ErrorHandler
// Created a JsonSerializerSettings and passed it to DeserializeObject
var jsonSettings = new JsonSerializerSettings { Error = ErrorHandler };
JsonConvert.DeserializeObject<ParkingOfferDetailsDTO>(responseJson, jsonSettings);
/// Actual handler method
List<string> errors = new List<string>();
private void ErrorHandler(object sender, ErrorEventArgs e)
{
errors.Add(e.ErrorContext.Error.Message);
e.ErrorContext.Handled = true;
}
This helped in two ways,
1) There is no exception thrown but the same error (exception) is passed to the error handler.
2) The (incomplete) serialized object is returned.
This pointed out which part of object serialization is causing an exception.
Now issue in my code/model. I have [Required] attribute on some properties. Not sure why but that caused the Deserialization error.

Issue deserializing stripe json response

I have made a class to deserialize stripe json response it works find but on some i am getting error :
Cannot convert null to a value type.
Even though i can see type is always there at the end.
This is the response:
{
"id": "evt_1Dezu4HJCcuwD0sbvkmV6bEb",
"object": "event",
"api_version": "2018-11-08",
"created": 1544252828,
"data": {
"object": {
"id": "sub_E7ExxxXGawn6cu",
"object": "subscription",
"application_fee_percent": null,
"billing": "charge_automatically",
"billing_cycle_anchor": 1544252827,
"cancel_at_period_end": false,
"canceled_at": null,
"created": 1544252827,
"current_period_end": 1544339227,
"current_period_start": 1544252827,
"customer": "cus_E7xxxQqowY9",
"days_until_due": null,
"default_source": null,
"discount": null,
"ended_at": null,
"items": {
"object": "list",
"data": [
{
"id": "si_E7EMDEdBnD6wUx",
"object": "subscription_item",
"created": 1544252828,
"metadata": {
},
"plan": {
"id": "plan_E5lRIPvrkNuRBB",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 0,
"billing_scheme": "per_unit",
"created": 1543997153,
"currency": "usd",
"interval": "day",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"nickname": "Free Plan",
"product": "prod_E1CBxxxpNa5Lf02d",
"tiers": null,
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"quantity": 1,
"subscription": "sub_E7xxxXGawn6cu"
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/subscription_items?subscription=sub_E7xxxXGawn6cu"
},
"livemode": false,
"metadata": {
},
"plan": {
"id": "plan_E5lRIPxxxkNuRBB",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 0,
"billing_scheme": "per_unit",
"created": 1543997153,
"currency": "usd",
"interval": "day",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"nickname": "Free Plan",
"product": "prod_E1CBZpNa5Lf02d",
"tiers": null,
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"quantity": 1,
"start": 1544252827,
"status": "active",
"tax_percent": null,
"trial_end": null,
"trial_start": null
}
},
"livemode": false,
"pending_webhooks": 1,
"request": {
"id": "req_OJV215KMm",
"idempotency_key": null
},
"type": "customer.subscription.created"
}
And class :
public class WebHookObjec
{
public int created { get; set; }
public bool livemode { get; set; }
public string id { get; set; }
public string #object { get; set; }
public object request { get; set; }
public string type { get; set; }
public int pending_webhooks { get; set; }
public string api_version { get; set; }
public Data data { get; set; }
public class Metadata
{
}
public class Plan
{
public string id { get; set; }
public string #object { get; set; }
public bool active { get; set; }
public object aggregate_usage { get; set; }
public int amount { get; set; }
public string billing_scheme { get; set; }
public int created { get; set; }
public string currency { get; set; }
public string interval { get; set; }
public int interval_count { get; set; }
public bool livemode { get; set; }
public Metadata metadata { get; set; }
public string nickname { get; set; }
public string product { get; set; }
public object tiers { get; set; }
public object tiers_mode { get; set; }
public object transform_usage { get; set; }
public int trial_period_days { get; set; }
public string usage_type { get; set; }
}
public class Phase
{
public object application_fee_percent { get; set; }
public object coupon { get; set; }
public int end_date { get; set; }
public List<Plan> plans { get; set; }
public int start_date { get; set; }
public object tax_percent { get; set; }
public bool trial { get; set; }
public object trial_end { get; set; }
}
public class PreviousAttributes
{
public string status { get; set; }
}
public class Object
{
public string id { get; set; }
public string #object { get; set; }
public string billing { get; set; }
public object canceled_at { get; set; }
public object completed_at { get; set; }
public int created { get; set; }
public object current_phase { get; set; }
public string customer { get; set; }
public object invoice_settings { get; set; }
public bool livemode { get; set; }
public List<Phase> phases { get; set; }
public object released_at { get; set; }
public object released_subscription { get; set; }
public string renewal_behavior { get; set; }
public object renewal_interval { get; set; }
public string revision { get; set; }
public string status { get; set; }
public object subscription { get; set; }
public Plan plan { get; set; }
public int quantity { get; set; }
public int start { get; set; }
public object tax_percent { get; set; }
public int trial_end { get; set; }
public int trial_start { get; set; }
public int amount { get; set; }
public int amount_refunded { get; set; }
public object application { get; set; }
public object application_fee { get; set; }
public string balance_transaction { get; set; }
public bool captured { get; set; }
public string currency { get; set; }
public string description { get; set; }
public object destination { get; set; }
public object dispute { get; set; }
public object failure_code { get; set; }
public object failure_message { get; set; }
public FraudDetails fraud_details { get; set; }
public object invoice { get; set; }
public Metadata metadata { get; set; }
public object on_behalf_of { get; set; }
public object order { get; set; }
public object outcome { get; set; }
public bool paid { get; set; }
public object payment_intent { get; set; }
public object receipt_email { get; set; }
public object receipt_number { get; set; }
public bool refunded { get; set; }
public Refunds refunds { get; set; }
public object review { get; set; }
public object shipping { get; set; }
public Source source { get; set; }
public object source_transfer { get; set; }
public object statement_descriptor { get; set; }
public object transfer_group { get; set; }
}
public class Data
{
public Object #object { get; set; }
public PreviousAttributes previous_attributes { get; set; }
}
public class FraudDetails
{
}
public class Refunds
{
public string #object { get; set; }
public List<object> data { get; set; }
public bool has_more { get; set; }
public int total_count { get; set; }
public string url { get; set; }
}
public class Metadata2
{
}
public class Source
{
public string id { get; set; }
public string #object { get; set; }
public object address_city { get; set; }
public object address_country { get; set; }
public object address_line1 { get; set; }
public object address_line1_check { get; set; }
public object address_line2 { get; set; }
public object address_state { get; set; }
public object address_zip { get; set; }
public object address_zip_check { get; set; }
public string brand { get; set; }
public string country { get; set; }
public string customer { get; set; }
public string cvc_check { get; set; }
public object dynamic_last4 { get; set; }
public int exp_month { get; set; }
public int exp_year { get; set; }
public string fingerprint { get; set; }
public string funding { get; set; }
public string last4 { get; set; }
public Metadata2 metadata { get; set; }
public string name { get; set; }
public object tokenization_method { get; set; }
}
}
After analyzing your json and class objects for json.
You json contains property with name "trial_period_days": null, has been null and you declare its respective property of type integer public int trial_period_days { get; set; } in Plan class object.
So int is a value type and cannot be cast to null.
To get rid from this exception you need to modify your property to either of below.
public object trial_period_days { get; set; }
OR
public int? trial_period_days { get; set; }
And same for your remaining properties inside Object class for trial_start and trial_end.
Note: Don't use Object as your custom class name because it already predefined class in .net framework.
Because there are some properties are null in your JSON data but you use value type to carry it.
You can try to use string type to represent your null value properties for those models to carry your JSON data.
public class Metadata
{
}
public class Metadata2
{
}
public class Plan
{
public string id { get; set; }
public string #string { get; set; }
public bool active { get; set; }
public string aggregate_usage { get; set; }
public int amount { get; set; }
public string billing_scheme { get; set; }
public int created { get; set; }
public string currency { get; set; }
public string interval { get; set; }
public int interval_count { get; set; }
public bool livemode { get; set; }
public Metadata2 metadata { get; set; }
public string nickname { get; set; }
public string product { get; set; }
public string tiers { get; set; }
public string tiers_mode { get; set; }
public string transform_usage { get; set; }
public string trial_period_days { get; set; }
public string usage_type { get; set; }
}
public class Datum
{
public string id { get; set; }
public string #string { get; set; }
public int created { get; set; }
public Metadata metadata { get; set; }
public Plan plan { get; set; }
public int quantity { get; set; }
public string subscription { get; set; }
}
public class Items
{
public string #string { get; set; }
public List<Datum> data { get; set; }
public bool has_more { get; set; }
public int total_count { get; set; }
public string url { get; set; }
}
public class Metadata3
{
}
public class Metadata4
{
}
public class Plan2
{
public string id { get; set; }
public string #string { get; set; }
public bool active { get; set; }
public string aggregate_usage { get; set; }
public int amount { get; set; }
public string billing_scheme { get; set; }
public int created { get; set; }
public string currency { get; set; }
public string interval { get; set; }
public int interval_count { get; set; }
public bool livemode { get; set; }
public Metadata4 metadata { get; set; }
public string nickname { get; set; }
public string product { get; set; }
public string tiers { get; set; }
public string tiers_mode { get; set; }
public string transform_usage { get; set; }
public string trial_period_days { get; set; }
public string usage_type { get; set; }
}
public class content
{
public string id { get; set; }
public string #string { get; set; }
public string application_fee_percent { get; set; }
public string billing { get; set; }
public int billing_cycle_anchor { get; set; }
public bool cancel_at_period_end { get; set; }
public string canceled_at { get; set; }
public int created { get; set; }
public int current_period_end { get; set; }
public int current_period_start { get; set; }
public string customer { get; set; }
public string days_until_due { get; set; }
public string default_source { get; set; }
public string discount { get; set; }
public string ended_at { get; set; }
public Items items { get; set; }
public bool livemode { get; set; }
public Metadata3 metadata { get; set; }
public Plan2 plan { get; set; }
public int quantity { get; set; }
public int start { get; set; }
public string status { get; set; }
public string tax_percent { get; set; }
public string trial_end { get; set; }
public string trial_start { get; set; }
}
public class Data
{
public content #object { get; set; }
}
public class Request
{
public string id { get; set; }
public string idempotency_key { get; set; }
}
public class RootObject
{
public string id { get; set; }
public string #string { get; set; }
public string api_version { get; set; }
public int created { get; set; }
public Data data { get; set; }
public bool livemode { get; set; }
public int pending_webhooks { get; set; }
public Request request { get; set; }
public string type { get; set; }
}
use will be like this
var result =JsonConvert.DeserializeObject<RootObject>(data);
Note
There are two way can create model easily.
You can use Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as a class, you can easier to know the relation between Json and model.
If you can't use Web Essentials you can instead of use http://json2csharp.com/ online JSON to Model class.
You can try to use those models to carry your JSON Format.

How to read the json string through C# code in runtime?

{
"StudentInformation": {
"rollNumber": null,
"isClassLeader": false,
"result": "Pass"
},
"CollegeInformation": {
"allClass": ["A", "B"],
"currencyAccepted": "INR",
"calendarDates": [],
"currencyCode": "INR",
"collegeCode": null,
"hasBulidingFundPrices": false,
"hasHostel": false,
"hasSecurityFares": false
},
"Collegetrips": [{
"tripsdate": [{
"departureTripDate": "2017-08-15 00:00:00",
"Places": [{
"destination": "Bombay",
"price": [{
"priceAmount": 1726
}]
}]
}]
}]
}
In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?
You can use System.Web.Script.Serialization (you need to add a reference to System.Web.Extensions):
dynamic json = new JavaScriptSerializer()
.DeserializeObject(jsonString);
decimal price = json["Collegetrips"][0]
["tripsdate"][0]
["Places"][0]
["price"][0]
["priceAmount"]; // 1726
Note that you can pretty much traverse the json in this manner using indexes and key names.
Hi try this,
public void Main()
{
string sJSON = "{\"StudentInformation\": {\"rollNumber\": null,\"isClassLeader\": false,\"result\": \"Pass\"},\"CollegeInformation\": {\"allClass\": [\"A\", \"B\"],\"currencyAccepted\": \"INR\",\"calendarDates\": [],\"currencyCode\": \"INR\",\"collegeCode\": null,\"hasBulidingFundPrices\": false,\"hasHostel\": false,\"hasSecurityFares\": false},\"Collegetrips\": [{\"tripsdate\": [{\"departureTripDate\": \"2017-08-15 00:00:00\",\"Places\": [{\"destination\": \"Bombay\",\"price\": [{\"priceAmount\": 1726}]}]}]}]}";
Rootobject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(sJSON);
Price price = obj.Collegetrips.Select(ct =>
{
var r = ct.tripsdate.Select(td =>
{
var r1 = td.Places.Select(p =>
{
Price itemPrice = p.price.FirstOrDefault();
return itemPrice;
}).FirstOrDefault();
return r1;
}).FirstOrDefault();
return r;
}).FirstOrDefault();
if (price != null)
Console.Write(price.priceAmount);
else
Console.Write("Not Found!");
}
public class Rootobject
{
public Studentinformation StudentInformation { get; set; }
public Collegeinformation CollegeInformation { get; set; }
public Collegetrip[] Collegetrips { get; set; }
}
public class Studentinformation
{
public object rollNumber { get; set; }
public bool isClassLeader { get; set; }
public string result { get; set; }
}
public class Collegeinformation
{
public string[] allClass { get; set; }
public string currencyAccepted { get; set; }
public object[] calendarDates { get; set; }
public string currencyCode { get; set; }
public object collegeCode { get; set; }
public bool hasBulidingFundPrices { get; set; }
public bool hasHostel { get; set; }
public bool hasSecurityFares { get; set; }
}
public class Collegetrip
{
public Tripsdate[] tripsdate { get; set; }
}
public class Tripsdate
{
public string departureTripDate { get; set; }
public Place[] Places { get; set; }
}
public class Place
{
public string destination { get; set; }
public Price[] price { get; set; }
}
public class Price
{
public int priceAmount { get; set; }
}
I use:
http://json2csharp.com/
to get a class representing the Json Object.
public class StudentInformation
{
public object rollNumber { get; set; }
public bool isClassLeader { get; set; }
public string result { get; set; }
}
public class CollegeInformation
{
public List<string> allClass { get; set; }
public string currencyAccepted { get; set; }
public List<object> calendarDates { get; set; }
public string currencyCode { get; set; }
public object collegeCode { get; set; }
public bool hasBulidingFundPrices { get; set; }
public bool hasHostel { get; set; }
public bool hasSecurityFares { get; set; }
}
public class Price
{
public int priceAmount { get; set; }
}
public class Place
{
public string destination { get; set; }
public List<Price> price { get; set; }
}
public class Tripsdate
{
public string departureTripDate { get; set; }
public List<Place> Places { get; set; }
}
public class Collegetrip
{
public List<Tripsdate> tripsdate { get; set; }
}
public class JsonResponse
{
public StudentInformation StudentInformation { get; set; }
public CollegeInformation CollegeInformation { get; set; }
public List<Collegetrip> Collegetrips { get; set; }
}
After that I use Newtonsoft.Json to fill the Class:
using Newtonsoft.Json;
namespace GitRepositoryCreator.Common
{
class JObjects
{
public static string Get(object p_object)
{
return JsonConvert.SerializeObject(p_object);
}
internal static T Get<T>(string p_object)
{
return JsonConvert.DeserializeObject<T>(p_object);
}
}
}
You can call it like that:
JsonResponse jsonClass = JObjects.Get<JsonResponse>(stringJson);
string stringJson = JObjects.Get(jsonClass);
PS:
If your json variable name is no valid C# name you can fix that like this:
public class Exception
{
[JsonProperty(PropertyName = "$id")]
public string id { get; set; }
public object innerException { get; set; }
public string message { get; set; }
public string typeName { get; set; }
public string typeKey { get; set; }
public int errorCode { get; set; }
public int eventId { get; set; }
}

C# Check if JSON response contains key

I'm making an HTTP request that returns JSON but depending if the request is successful or not then the fields returned are different.
Consider the following snippet:
WebResponse response = moveItemRequest.GetResponse();
string stringResponse = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
stringResponse = reader.ReadToEnd();
}
// deserialize json response
MoveItemResponse moveItemResponse = JsonConvert.DeserializeObject<MoveItemResponse>(stringResponse);
The MoveItemResponse class:
public class MoveItemResponse
{
public string code;
public string reason;
public IList<ItemInfo> ItemInfo;
public MoveItemResponse()
{
ItemInfo = new List<ItemInfo>();
}
}
How am I able to check if a specific field is returned? Depending on if the request is successful then either code & reason will be returned, else itemInfo will be returned (where itemInfo is an object).
Fail Response:
{
"reason":"unlucky",
"message":null,
"code":460
}
Successful Response:
{
"errorState":null,
"credits":6310,
"itemInfo":[
{
"tradeId":717011415,
"itemData":{
"id":101619602325,
"timestamp":1447170628,
"formation":"f3412",
"untradeable":false,
"assetId":158023,
"rating":94,
"itemType":"player",
"resourceId":-2147325625,
"owners":1,
"discardValue":752,
"itemState":"forSale",
"cardsubtypeid":3,
"lastSalePrice":0,
"morale":50,
"fitness":99,
"injuryType":"none",
"injuryGames":0,
"preferredPosition":"RW",
"statsList":[
{
"value":0,
"index":0
},
{
"value":0,
"index":1
},
{
"value":0,
"index":2
},
{
"value":0,
"index":3
},
{
"value":0,
"index":4
}
],
"lifetimeStats":[
{
"value":0,
"index":0
},
{
"value":0,
"index":1
},
{
"value":0,
"index":2
},
{
"value":0,
"index":3
},
{
"value":0,
"index":4
}
],
"training":0,
"contract":7,
"suspension":0,
"attributeList":[
{
"value":92,
"index":0
},
{
"value":88,
"index":1
},
{
"value":86,
"index":2
},
{
"value":95,
"index":3
},
{
"value":24,
"index":4
},
{
"value":62,
"index":5
}
],
"teamid":241,
"rareflag":1,
"playStyle":250,
"leagueId":53,
"assists":0,
"lifetimeAssists":0,
"loyaltyBonus":1,
"pile":5,
"nation":52
},
"tradeState":"active",
"buyNowPrice":1726000,
"currentBid":0,
"offers":0,
"watched":null,
"bidState":"none",
"startingBid":426000,
"confidenceValue":100,
"expires":3212,
"sellerName":"FIFA UT",
"sellerEstablished":0,
"sellerId":0,
"tradeOwner":false
}
],
"duplicateItemIdList":null,
"bidTokens":{
},
"currencies":[
{
"name":"COINS",
"funds":6310,
"finalFunds":6310
},
{
"name":"POINTS",
"funds":0,
"finalFunds":0
},
{
"name":"DRAFT_TOKEN",
"funds":0,
"finalFunds":0
}
]
}
Secondly, do I need to do the StreamReader to declare the returned JSON to a string before deserializing it?
I think there are couple of ways to handle this, like:
Do IndexOf inside the string and decide if the property is there or not?
For example:
if (response.IndexOf("\"code\":", StringComparison.CurrentCultureIgnoreCase) > 0) /*assumption properties are inside double quotes*/
{
//Do things for error
}
else
{
//Do things for success
}
Have a class which has properties for both success and failure case and now based on the property representing the value for Error decide whether it passed or not
For example:
var instance = JsonConvert.DeserializeObject<RootObject>(response);
if (instance.code != 0)
{
//Do things for error
}
else
{
//Do things for success
}
I have tried to do the second option with the below code so give this code a try. I have created mock classes based on your sample data using json2csharp. I hope I have understood your question.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
var responses = new string[] { #"{""reason"":""unlucky"",""message"":null,""code"":460}",
#"{""errorState"":null,""credits"":6310,""itemInfo"":[{""tradeId"":717011415,""itemData"":{""id"":101619602325
,""timestamp"":1447170628,""formation"":""f3412"",""untradeable"":false,""assetId"":158023,""rating"":94,""itemType""
:""player"",""resourceId"":-2147325625,""owners"":1,""discardValue"":752,""itemState"":""forSale"",""cardsubtypeid""
:3,""lastSalePrice"":0,""morale"":50,""fitness"":99,""injuryType"":""none"",""injuryGames"":0,""preferredPosition""
:""RW"",""statsList"":[{""value"":0,""index"":0},{""value"":0,""index"":1},{""value"":0,""index"":2},{""value"":0,""index""
:3},{""value"":0,""index"":4}],""lifetimeStats"":[{""value"":0,""index"":0},{""value"":0,""index"":1},{""value"":0,""index""
:2},{""value"":0,""index"":3},{""value"":0,""index"":4}],""training"":0,""contract"":7,""suspension"":0,""attributeList""
:[{""value"":92,""index"":0},{""value"":88,""index"":1},{""value"":86,""index"":2},{""value"":95,""index"":3},{""value""
:24,""index"":4},{""value"":62,""index"":5}],""teamid"":241,""rareflag"":1,""playStyle"":250,""leagueId"":53,""assists""
:0,""lifetimeAssists"":0,""loyaltyBonus"":1,""pile"":5,""nation"":52},""tradeState"":""active"",""buyNowPrice"":1726000
,""currentBid"":0,""offers"":0,""watched"":null,""bidState"":""none"",""startingBid"":426000,""confidenceValue"":100
,""expires"":3212,""sellerName"":""FIFA UT"",""sellerEstablished"":0,""sellerId"":0,""tradeOwner"":false}],""duplicateItemIdList""
:null,""bidTokens"":{},""currencies"":[{""name"":""COINS"",""funds"":6310,""finalFunds"":6310},{""name"":""POINTS""
,""funds"":0,""finalFunds"":0},{""name"":""DRAFT_TOKEN"",""funds"":0,""finalFunds"":0}]}" };
foreach (var response in responses)
{
var instance = JsonConvert.DeserializeObject<RootObject>(response);
if (instance.code != 0)
{
//Do things for error
}
else
{
//Do things for success
}
}
}
}
public class StatsList
{
public int value { get; set; }
public int index { get; set; }
}
public class LifetimeStat
{
public int value { get; set; }
public int index { get; set; }
}
public class AttributeList
{
public int value { get; set; }
public int index { get; set; }
}
public class ItemData
{
public long id { get; set; }
public int timestamp { get; set; }
public string formation { get; set; }
public bool untradeable { get; set; }
public int assetId { get; set; }
public int rating { get; set; }
public string itemType { get; set; }
public int resourceId { get; set; }
public int owners { get; set; }
public int discardValue { get; set; }
public string itemState { get; set; }
public int cardsubtypeid { get; set; }
public int lastSalePrice { get; set; }
public int morale { get; set; }
public int fitness { get; set; }
public string injuryType { get; set; }
public int injuryGames { get; set; }
public string preferredPosition { get; set; }
public List<StatsList> statsList { get; set; }
public List<LifetimeStat> lifetimeStats { get; set; }
public int training { get; set; }
public int contract { get; set; }
public int suspension { get; set; }
public List<AttributeList> attributeList { get; set; }
public int teamid { get; set; }
public int rareflag { get; set; }
public int playStyle { get; set; }
public int leagueId { get; set; }
public int assists { get; set; }
public int lifetimeAssists { get; set; }
public int loyaltyBonus { get; set; }
public int pile { get; set; }
public int nation { get; set; }
}
public class ItemInfo
{
public int tradeId { get; set; }
public ItemData itemData { get; set; }
public string tradeState { get; set; }
public int buyNowPrice { get; set; }
public int currentBid { get; set; }
public int offers { get; set; }
public object watched { get; set; }
public string bidState { get; set; }
public int startingBid { get; set; }
public int confidenceValue { get; set; }
public int expires { get; set; }
public string sellerName { get; set; }
public int sellerEstablished { get; set; }
public int sellerId { get; set; }
public bool tradeOwner { get; set; }
}
public class BidTokens
{
}
public class Currency
{
public string name { get; set; }
public int funds { get; set; }
public int finalFunds { get; set; }
}
public class RootObject
{
public string reason { get; set; }
public object message { get; set; }
public int code { get; set; }
public object errorState { get; set; }
public int credits { get; set; }
public List<ItemInfo> itemInfo { get; set; }
public object duplicateItemIdList { get; set; }
public BidTokens bidTokens { get; set; }
public List<Currency> currencies { get; set; }
public override string ToString()
{
return $"Contains Error: {code != 0}";
}
}
}

Categories