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.
Related
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.
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.
Greetings I have the following problem it turns out that I try to deserialize a json with the newtonsoft library with the following line
Tramite body = JsonConvert.DeserializeObject < Tramite> (JsonBody);
Json which is sent:
{
"body":[
{
"id":3772,
"processInstanceId":"1416",
"tipoTramite":{
"id":1,
"descripcion":"Solicitud Patente Comercial (Municipalidad)"
},
"canal":{
"id":0,
"nombre":""
},
"definicionTramite":{
"id":282,
"tipoTramite":null,
"idEstado":0,
"version":3,
"idDepartamento":0,
"idArea":0,
"nombre":"Solicitud Patente Comercial (Municipalidad)",
"codigo":null,
"descripcion":null,
"deploymentId":null,
"configuracion":null,
"processId":null
},
"institucion":{
"id":1045,
"idInstitucionBase":null,
"tipoInstitucion":null,
"nombre":"Municipalidad de La Granja",
"codigo":"LAGRANJA",
"direccion":null,
"logoWeb":null,
"logoPdf":null,
"telefonoFijo":null,
"email":null,
"propietario":null
},
"idDepartamento":1,
"idArea":3,
"estado":{
"id":294,
"definicionTramite":{
"id":282,
"tipoTramite":null,
"idEstado":0,
"version":0,
"idDepartamento":0,
"idArea":0,
"nombre":null,
"codigo":null,
"descripcion":null,
"deploymentId":null,
"configuracion":null,
"processId":null
},
"codigo":"03",
"nombre":"En Proceso"
},
"cve":"3df31748ec86df4280ecfaa853ead07a8918b345",
"numeroSolicitud":"555",
"tarifa":0,
"rut":{
"numero":13639987,
"dv":"K"
},
"rutEmpresa":{
"numero":76291578,
"dv":"2"
},
"nombre":"Solicitud Patente Comercial (Municipalidad)",
"flagPagado":false,
"fechaCreacion":1508792522683,
"fechaModificacion":1508792809726,
"datosTramite":[
{
"id":0,
"key":"inmueble_direccion_numero",
"tipo":"string",
"data":"3334"
}
],
"deploymenId":"cl.corfo.municipiogenerico:bpm-patentegenerica:1.4",
"processId":"patenteGenerica",
"solicitante":"FÉLIX EDUARDO CIFUENTES CID",
"contribuyente":"NombreMock de Fantasia",
"keyConfiguracion":"patente-comercial-ampliacion-giro"
}
]
}
This is the object: https://i.stack.imgur.com/MTT9s.png
Clase que serializo:
public int id { get; set; }
public string processInstanceId { get; set; }
Dictionary<string, string> tipoTramite { get; set; }
Dictionary<string, string> canal { get; set; }
public DefinicionTramite definicionTramite { get; set; }
public Institucion institucion { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public Estado estado { get; set; }
public string cve { get; set; }
public string numeroSolicitud { get; set; }
public double tarifa { get; set; }
Dictionary<string, string> rut { get; set; }
Dictionary<string, string> rutEmpresa { get; set; }
public string nombre { get; set; }
public bool flagPagado { get; set; }
public string fechaCreacion { get; set; }
public string fechaModificacion { get; set; }
public List<DatosTramite> datosTramite { get; set; }
public string deploymenId { get; set; }
public string processId { get; set; }
public string solicitante { get; set; }
public string contribuyente { get; set; }
public string keyConfiguracion { get; set; }
class Definicion Tramite
public int id { get; set; }
public string tipoTramite { get; set; }
public int idEstado { get; set; }
public int version { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public string nombre { get; set; }
public string codigo { get; set; }
public string descripcion { get; set; }
public string deploymentId { get; set; }
public string configuracion { get; set; }
public string processId { get; set; }
class Institucion
public int id { get; set; }
public string idInstitucionBase { get; set; }
public string tipoInstitucion { get; set; }
public string nombre { get; set; }
public string codigo { get; set; }
public string direccion { get; set; }
public string logoWeb { get; set; }
public string logoPdf { get; set; }
public string telefonoFijo { get; set; }
public string email { get; set; }
public string propietario { get; set; }
class Estado
public int id { get; set; }
public DefinicionTramite definicionTramite { get; set; }
public string codigo { get; set; }
public string nombre { get; set; }
class Datos Tramite
public int id { get; set; }
public string key { get; set; }
public string tipo { get; set; }
public string data { get; set; }
These are all the classes that are involved in the deserialization of the json that I sent, I tried to deserialize a dataSet but it also could not because of the classes it contained (according to what I read in a stackoverflow question) if someone knows that I am bad or if there is another way of doing the deserialization of a json in C# helps me
This worked for me:
JsonConvert.DeserializeObject<Rootobject>(json)
Here are the classes that I created:
public class Rootobject
{
public Body[] body { get; set; }
}
public class Body
{
public int id { get; set; }
public string processInstanceId { get; set; }
public Tipotramite tipoTramite { get; set; }
public Canal canal { get; set; }
public Definiciontramite definicionTramite { get; set; }
public Institucion institucion { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public Estado estado { get; set; }
public string cve { get; set; }
public string numeroSolicitud { get; set; }
public int tarifa { get; set; }
public Rut rut { get; set; }
public Rutempresa rutEmpresa { get; set; }
public string nombre { get; set; }
public bool flagPagado { get; set; }
public long fechaCreacion { get; set; }
public long fechaModificacion { get; set; }
public Datostramite[] datosTramite { get; set; }
public string deploymenId { get; set; }
public string processId { get; set; }
public string solicitante { get; set; }
public string contribuyente { get; set; }
public string keyConfiguracion { get; set; }
}
public class Tipotramite
{
public int id { get; set; }
public string descripcion { get; set; }
}
public class Canal
{
public int id { get; set; }
public string nombre { get; set; }
}
public class Definiciontramite
{
public int id { get; set; }
public object tipoTramite { get; set; }
public int idEstado { get; set; }
public int version { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public string nombre { get; set; }
public object codigo { get; set; }
public object descripcion { get; set; }
public object deploymentId { get; set; }
public object configuracion { get; set; }
public object processId { get; set; }
}
public class Institucion
{
public int id { get; set; }
public object idInstitucionBase { get; set; }
public object tipoInstitucion { get; set; }
public string nombre { get; set; }
public string codigo { get; set; }
public object direccion { get; set; }
public object logoWeb { get; set; }
public object logoPdf { get; set; }
public object telefonoFijo { get; set; }
public object email { get; set; }
public object propietario { get; set; }
}
public class Estado
{
public int id { get; set; }
public Definiciontramite1 definicionTramite { get; set; }
public string codigo { get; set; }
public string nombre { get; set; }
}
public class Definiciontramite1
{
public int id { get; set; }
public object tipoTramite { get; set; }
public int idEstado { get; set; }
public int version { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public object nombre { get; set; }
public object codigo { get; set; }
public object descripcion { get; set; }
public object deploymentId { get; set; }
public object configuracion { get; set; }
public object processId { get; set; }
}
public class Rut
{
public int numero { get; set; }
public string dv { get; set; }
}
public class Rutempresa
{
public int numero { get; set; }
public string dv { get; set; }
}
public class Datostramite
{
public int id { get; set; }
public string key { get; set; }
public string tipo { get; set; }
public string data { get; set; }
}
You need to see your JSON and figure out that body is an array and a root. Hence there must be a root class with body as an array. Create that and then deserialize. That must work
First of all, your C# model is not entirely same as your JSON. For Example, tipoTramite in your main class and Json object are different. Secondly, the reason why you are getting everything null here is you are sending an array of object in the json but at the server level, you are deserializing the object. You could do one of the following:
1.Send JSON as object and not as array like below, and then your code should work
{
"body":{
"id":3772,
"processInstanceId":"1416",
...
...
...
}
2.If you don't want to change the json, then for deserializing, you will have to create a class that contains the array of Tramite type and then use that class to deserialize the json:
public class TramiteJsonModel{
public Tramite[] Body {get;set;}
}
Now use the code below to deserialize the content:
TramiteJsonModel body = JsonConvert.DeserializeObject <TramiteJsonModel> (JsonBody);
I have a JSON with multidimensional array. I have no idea how to deserialize it on my c# model. I did a very simple way of deserialization which is not working. I need to know how to deserialize my JSON on more structural way.
This is my json data
{
"Access_point_result": [
{
"msg": {
"ap_eth_mac": {
"addr": "D8C7C8C0C7BE"
},
"ap_name": "1344-1-AL5",
"ap_group": "1344-hq",
"ap_model": "135",
"depl_mode": "DEPLOYMENT_MODE_CAMPUS",
"ap_ip_address": {
"af": "ADDR_FAMILY_INET",
"addr": "10.6.66.67",
"reboots": 1,
"rebootstraps": 2,
"managed_by": {
"af": "ADDR_FAMILY_INET",
"addr": "0.0.0.0"
},
"managed_by_key": "2e302bee0164cc154d1d266d8567ada44d49e77af82f4b5ccb",
"radios": {
"radio_bssid.addr": "D8.C7.C8.46.D8.10"
},
"is_master": true,
"ap_location": {
"ap_eth_mac": "D8C7C8C0C7BE",
"campus_id": "6F9DEC79839D458B9F148D16A46A353E",
"building_id": "83393A922FB249C1929B95393A2AAFDA",
"floor_id": "260BE76B0DD13E7AAF18EB3B47DD7F7B",
"longitude": -122.008,
"latitude": 37.4129,
"ap_x": 22.15,
"ap_y": 99.18
}
},
"ts": 1382046667
}
}
]
}
Below is my C# model
public class WifiDataAruba : BaseModel
{
public string APMACAddr { get; set; }
public string APName { get; set; }
public string APGroup { get; set; }
public string APModel { get; set; }
public string APDeplMode { get; set; }
public string APIPAddr { get; set; }
public int APReboots { get; set; }
public int APRebootStraps { get; set; }
public string APManagedBy { get; set; }
public string APManagedByKey { get; set; }
public string APRadios { get; set; }
public bool APMaster { get; set; }
public string APLocation { get; set; }
public string APMACAddr2 { get; set; }
public string APCampusID { get; set; }
public string APLocationID { get; set; }
public string APBuildingID { get; set; }
public string APFloorID { get; set; }
public double APLongtitude { get; set; }
public double APLatitude { get; set; }
public double X { get; set; }
public double Y { get; set; }
public DateTime ImportTimestamp { get; set; }
}
How can i make the break the deserialization much structural way?
you have to change your model to the following
public class ApEthMac
{
public string addr { get; set; }
}
public class ManagedBy
{
public string af { get; set; }
public string addr { get; set; }
}
public class Radios
{
public string __invalid_name__radio_bssid.addr { get; set; }
}
public class ApLocation
{
public string ap_eth_mac { get; set; }
public string campus_id { get; set; }
public string building_id { get; set; }
public string floor_id { get; set; }
public double longitude { get; set; }
public double latitude { get; set; }
public double ap_x { get; set; }
public double ap_y { get; set; }
}
public class ApIpAddress
{
public string af { get; set; }
public string addr { get; set; }
public int reboots { get; set; }
public int rebootstraps { get; set; }
public ManagedBy managed_by { get; set; }
public string managed_by_key { get; set; }
public Radios radios { get; set; }
public bool is_master { get; set; }
public ApLocation ap_location { get; set; }
}
public class Msg
{
public ApEthMac ap_eth_mac { get; set; }
public string ap_name { get; set; }
public string ap_group { get; set; }
public string ap_model { get; set; }
public string depl_mode { get; set; }
public ApIpAddress ap_ip_address { get; set; }
public int ts { get; set; }
}
public class AccessPointResult
{
public Msg msg { get; set; }
}
public class RootObject
{
public List<AccessPointResult> Access_point_result { get; set; }
}
and your webapi method should look like the following
public void Post(RootObject rootObject)
Note
that you have to add camelcaseconvention in your webapi config if you want to change your c# model to PascalCase
Here how your method should look like in your WebaApiConfig
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
EnableCrossSiteRequests(config);
// Web API routes
config.MapHttpAttributeRoutes();
GlobalConfiguration.Configuration.Formatters.JsonFormatter
.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Model
public class ApEthMac
{
public string addr { get; set; }
}
public class ManagedBy
{
public string af { get; set; }
public string addr { get; set; }
}
public class Radios
{
public string __invalid_name__radio_bssid.addr { get; set; }
}
public class ApLocation
{
public string ap_eth_mac { get; set; }
public string campus_id { get; set; }
public string building_id { get; set; }
public string floor_id { get; set; }
public double longitude { get; set; }
public double latitude { get; set; }
public double ap_x { get; set; }
public double ap_y { get; set; }
}
public class ApIpAddress
{
public string af { get; set; }
public string addr { get; set; }
public int reboots { get; set; }
public int rebootstraps { get; set; }
public ManagedBy managed_by { get; set; }
public string managed_by_key { get; set; }
public Radios radios { get; set; }
public bool is_master { get; set; }
public ApLocation ap_location { get; set; }
}
public class Msg
{
public ApEthMac ap_eth_mac { get; set; }
public string ap_name { get; set; }
public string ap_group { get; set; }
public string ap_model { get; set; }
public string depl_mode { get; set; }
public ApIpAddress ap_ip_address { get; set; }
public int ts { get; set; }
}
public class AccessPointResult
{
public Msg msg { get; set; }
}
public class RootObject
{
public List<AccessPointResult> Access_point_result { get; set; }
}
then DeserializeObject
RootObject rootObject= new RootObject();
rootObject= JsonConvert.DeserializeObject<RootObject>(jsonAgents);
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.