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.
Related
I'm trying to create a basic Xamarin Forms app that can list available gateways on my PFsense firewall, Show the available gateway and change this to another gateway to route through if required. The problem I have is I cannot deserialize the JSON in C# because each object has a different object name:
{
"status": "ok",
"code": 200,
"return": 0,
"message": "Success",
"data": {
"GW_WAN_1": {
"interface": "hn0",
"gateway": "192.168.0.1",
"name": "GW_WAN_1",
"weight": "1",
"ipprotocol": "inet",
"interval": "500",
"time_period": "60000",
"alert_interval": "1000",
"descr": "Interface wan Gateway",
"data_payload": "1",
"latencylow": "200",
"latencyhigh": "500",
"losslow": "10",
"losshigh": "20",
"loss_interval": "2000",
"monitor": "192.168.0.1",
"friendlyiface": "wan",
"friendlyifdescr": "RED",
"isdefaultgw": true,
"attribute": 0,
"tiername": "Default (IPv4)"
},
"INT1_DHCP6": {
"dynamic": true,
"ipprotocol": "inet6",
"gateway": "fe80::1af1:45ff:fe90:4b13",
"interface": "hn0",
"friendlyiface": "wan",
"friendlyifdescr": "RED",
"name": "INT1_DHCP6",
"attribute": "system",
"isdefaultgw": true,
"monitor": "fe80::1af1:45ff:fe90:4b13",
"descr": "Interface RED_DHCP6 Gateway",
"tiername": ""
},
"VPN_EUR_1": {
"interface": "ovpns1",
"gateway": "192.168.1.2",
"name": "VPN_EUR_1",
"weight": "1",
"ipprotocol": "inet",
"interval": "500",
"time_period": "60000",
"alert_interval": "1000",
"descr": "Interface VPN_EUR_1 Gateway",
"data_payload": "1",
"latencylow": "200",
"latencyhigh": "500",
"losslow": "10",
"losshigh": "20",
"loss_interval": "2000",
"dynamic": true,
"monitor": "192.168.1.2",
"friendlyiface": "opt4",
"friendlyifdescr": "VPN_EUR_1",
"attribute": 1,
"tiername": ""
},
"Null4": {
"name": "Null4",
"interface": "lo0",
"ipprotocol": "inet",
"gateway": "127.0.0.1",
"attribute": "system",
"tiername": ""
},
"Null6": {
"name": "Null6",
"interface": "lo0",
"ipprotocol": "inet6",
"gateway": "::1",
"attribute": "system",
"tiername": ""
},
"VPN_EUR_1V6": {
"dynamic": false,
"ipprotocol": "inet6",
"gateway": null,
"interface": "ovpns1",
"friendlyiface": "opt4",
"friendlyifdescr": "VPN_EUR_1",
"name": "VPN_EUR_1V6",
"attribute": "system",
"descr": "Interface VPN_EUR_1V6 Gateway",
"tiername": ""
}
}
}
Here's how I've gone about trying to deserialize:
string authHeader = Constants.AUTH_HEADER;
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authHeader);
var response = await client.GetAsync(Constants.GATEWAY);
var json = await response.Content.ReadAsStringAsync();
var gateways = JsonConvert.DeserializeObject<Data>(json);
The C# Object (Generated using json to C# converter):
public class GW_WAN_1
{
public string #interface { get; set; }
public string gateway { get; set; }
public string name { get; set; }
public string weight { get; set; }
public string ipprotocol { get; set; }
public string interval { get; set; }
public string time_period { get; set; }
public string alert_interval { get; set; }
public string descr { get; set; }
public string data_payload { get; set; }
public string latencylow { get; set; }
public string latencyhigh { get; set; }
public string losslow { get; set; }
public string losshigh { get; set; }
public string loss_interval { get; set; }
public string monitor { get; set; }
public string friendlyiface { get; set; }
public string friendlyifdescr { get; set; }
public bool isdefaultgw { get; set; }
public int attribute { get; set; }
public string tiername { get; set; }
}
public class INT1_DHCP6
{
public bool dynamic { get; set; }
public string ipprotocol { get; set; }
public string gateway { get; set; }
public string #interface { get; set; }
public string friendlyiface { get; set; }
public string friendlyifdescr { get; set; }
public string name { get; set; }
public string attribute { get; set; }
public bool isdefaultgw { get; set; }
public string monitor { get; set; }
public string descr { get; set; }
public string tiername { get; set; }
}
public class VPN_EUR_1
{
public string #interface { get; set; }
public string gateway { get; set; }
public string name { get; set; }
public string weight { get; set; }
public string ipprotocol { get; set; }
public string interval { get; set; }
public string time_period { get; set; }
public string alert_interval { get; set; }
public string descr { get; set; }
public string data_payload { get; set; }
public string latencylow { get; set; }
public string latencyhigh { get; set; }
public string losslow { get; set; }
public string losshigh { get; set; }
public string loss_interval { get; set; }
public bool dynamic { get; set; }
public string monitor { get; set; }
public string friendlyiface { get; set; }
public string friendlyifdescr { get; set; }
public int attribute { get; set; }
public string tiername { get; set; }
}
public class Null4
{
public string name { get; set; }
public string #interface { get; set; }
public string ipprotocol { get; set; }
public string gateway { get; set; }
public string attribute { get; set; }
public string tiername { get; set; }
}
public class Null6
{
public string name { get; set; }
public string #interface { get; set; }
public string ipprotocol { get; set; }
public string gateway { get; set; }
public string attribute { get; set; }
public string tiername { get; set; }
}
public class VPN_EUR_1V6
{
public bool dynamic { get; set; }
public string ipprotocol { get; set; }
public object gateway { get; set; }
public string #interface { get; set; }
public string friendlyiface { get; set; }
public string friendlyifdescr { get; set; }
public string name { get; set; }
public string attribute { get; set; }
public string descr { get; set; }
public string tiername { get; set; }
}
public class Data
{
public GW_WAN_1 GW_WAN { get; set; }
public INT1_DHCP6 INT1_DHCP6 { get; set; }
public VPN_EUR_1 VPN_EUR_1 { get; set; }
public Null4 Null4 { get; set; }
public Null6 Null6 { get; set; }
public VPN_EUR_1V6 VPN_NL_VPNV6 { get; set; }
}
public class Root
{
public string status { get; set; }
public int code { get; set; }
public int #return { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
The problem is in the gateways variable, all of the properties are null. I think because of how the JSON is structured in the response, it might not be possible in C#, but perhaps there's another way of going about it?
The API for the firewall is here:
https://github.com/jaredhendrickson13/pfsense-api
Thanks
I am new to C# with JSON. I would like to select with Nvidia API, the "featuredProduct" part, but I have an error
Cannot access child value on Newtonsoft.Json.Linq.JProperty.
This code works for the "searchedProducts" part.
Can you explain to me why?
const string url = "";
const int refresh = 3000;
string json = getGpuFromNvidia(url);
var jsonParse = JObject.Parse(json);
var result = jsonParse["searchedProducts"]["featuredProduct"]
.Where(n => n["isFounderEdition"].Value<bool>() == true)
.Select(p => new CarteGraphique
{
displayName = (string)p["displayName"],
prdStatus = (string)p["prdStatus"],
directPurchaseLink = (string)p["retailers"][0]["directPurchaseLink"]
})
.ToList();
I tested this code in VS
string json = ...your code
var jsonObj = JsonConvert.DeserializeObject<NvidiaRoot>(json);
var result = jsonObj.searchedProducts.productDetails
.Where(n => n.isFounderEdition)
.Select(p => new
{
displayName = p.displayName,
prdStatus = p.prdStatus,
directPurchaseLink = p.retailers[0].directPurchaseLink
})
.ToList();
OUTPUT
[
{
"displayName": "NVIDIA RTX 3090",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB89455870.html"
},
{
"displayName": "NVIDIA RTX 3070",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB74221588.html"
},
{
"displayName": "NVIDIA RTX 3060 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB54012144.html"
},
{
"displayName": "NVIDIA RTX 3070 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": null
},
{
"displayName": "NVIDIA RTX 3080 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": null
}
]
UPDATE
if you need just a feature product
var featuredProduct = jsonObj.searchedProducts.featuredProduct;
var result = new
{
displayName = featuredProduct.displayName,
prdStatus = featuredProduct.prdStatus,
directPurchaseLink = featuredProduct.retailers[0].directPurchaseLink
};
Short OUTPUT
{
"displayName": "NVIDIA RTX 3080",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB15921567.html"
}
Full OUTPUT
var result = jsonObj.searchedProducts.featuredProduct;
{
"displayName": "NVIDIA RTX 3080",
"totalCount": 1,
"productID": 30045,
"imageURL": "https://assets.nvidia.partners/images/png/nvidia-geforce-rtx-3080.png",
"productTitle": "NVIDIA GEFORCE RTX 3080",
"digitialRiverID": "",
"productSKU": "NVGFT080",
"productUPC": "NVGFT080_FR",
"productUPCOriginal": "NVGFT080",
"productPrice": "€719.00",
"productAvailable": false,
"productRating": null,
"customerReviewCount": null,
"isFounderEdition": true,
"isFeaturedProduct": true,
"certified": false,
"manufacturer": "NVIDIA",
"locale": "FR",
"isFeaturedProdcutFoundInSecondSearch": false,
"category": "GPU",
"gpu": "RTX 3080",
"purchaseOption": "",
"prdStatus": "out_of_stock",
"minShipDays": null,
"maxShipDays": null,
"shipInfo": null,
"isOffer": false,
"offerText": "",
"retailers": [
{
"productId": 30045,
"productTitle": "NVIDIA GEFORCE RTX 3080",
"logoUrl": "https://assets.nvidia.partners/logos/geforce/retailer-ldlc.png",
"isAvailable": true,
"salePrice": "719.00",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB15921567.html",
"purchaseLink": "https://www.ldlc.com/fiche/PB15921567.html",
"hasOffer": false,
"offerText": null,
"partnerId": "45",
"storeId": "45",
"upc": "NVGFT080_FR",
"sku": "NVGFT080",
"stock": 0,
"retailerName": "https://www.ldlc.com",
"type": 80
}
],
"productInfo": [
{
"name": "cooling_system",
"value": "Fan"
},
{
"name": "gpu_boost_clock_speed",
"value": "1.71 GHz"
},
{
"name": "gpu_memory_size",
"value": "10 GB"
}
],
"compareProductInfo": [
{
"name": "cooling_system",
"value": "Fan"
},
{
"name": "gpu_clock_speed",
"value": "1.44 GHz"
},
{
"name": "gpu_boost_clock_speed",
"value": "1.71 GHz"
},
{
"name": "gpu_memory_size",
"value": "10 GB"
}
]
}
classes
public class NvidiaRoot
{
public object categories { get; set; }
public List<Filter> filters { get; set; }
public object filterGroups { get; set; }
public object search { get; set; }
public string version { get; set; }
public List<Sort> sort { get; set; }
public Pagination pagination { get; set; }
public SearchedProducts searchedProducts { get; set; }
public Disclaimer disclaimer { get; set; }
}
public class FilterValue
{
public string dispValue { get; set; }
public object dispValueDesription { get; set; }
public object groupType { get; set; }
public int units { get; set; }
public bool #checked { get; set; }
public object imageURL { get; set; }
public bool isValidate { get; set; }
}
public class Filter
{
public string displayName { get; set; }
public string filterField { get; set; }
public string displayMaxValues { get; set; }
public string fieldType { get; set; }
public int? selectedMinRangeVal { get; set; }
public int? selectedMaxRangeVal { get; set; }
public int? defaultMinRangeVal { get; set; }
public int? defaultMaxRangeVal { get; set; }
public string unitsOfMeasure { get; set; }
public bool #checked { get; set; }
public object units { get; set; }
public List<FilterValue> filterValues { get; set; }
public string dataType { get; set; }
public bool showCount { get; set; }
public int filterDisplayOrder { get; set; }
}
public class Sort
{
public string displayName { get; set; }
public string value { get; set; }
public bool selected { get; set; }
}
public class Pagination
{
public int page { get; set; }
public int limit { get; set; }
public int totalRecords { get; set; }
public bool featuredProductIncludedInCount { get; set; }
}
public class Retailer
{
public int productId { get; set; }
public string productTitle { get; set; }
public string logoUrl { get; set; }
public bool isAvailable { get; set; }
public string salePrice { get; set; }
public string directPurchaseLink { get; set; }
public string purchaseLink { get; set; }
public bool hasOffer { get; set; }
public object offerText { get; set; }
public string partnerId { get; set; }
public string storeId { get; set; }
public string upc { get; set; }
public string sku { get; set; }
public int stock { get; set; }
public string retailerName { get; set; }
public int type { get; set; }
}
public class ProductInfo
{
public string name { get; set; }
public string value { get; set; }
}
public class CompareProductInfo
{
public string name { get; set; }
public string value { get; set; }
}
public class FeaturedProduct
{
public string displayName { get; set; }
public int totalCount { get; set; }
public int productID { get; set; }
public string imageURL { get; set; }
public string productTitle { get; set; }
public string digitialRiverID { get; set; }
public string productSKU { get; set; }
public string productUPC { get; set; }
public string productUPCOriginal { get; set; }
public string productPrice { get; set; }
public bool productAvailable { get; set; }
public object productRating { get; set; }
public object customerReviewCount { get; set; }
public bool isFounderEdition { get; set; }
public bool isFeaturedProduct { get; set; }
public bool certified { get; set; }
public string manufacturer { get; set; }
public string locale { get; set; }
public bool isFeaturedProdcutFoundInSecondSearch { get; set; }
public string category { get; set; }
public string gpu { get; set; }
public string purchaseOption { get; set; }
public string prdStatus { get; set; }
public object minShipDays { get; set; }
public object maxShipDays { get; set; }
public object shipInfo { get; set; }
public bool isOffer { get; set; }
public string offerText { get; set; }
public List<Retailer> retailers { get; set; }
public List<ProductInfo> productInfo { get; set; }
public List<CompareProductInfo> compareProductInfo { get; set; }
}
public class ProductDetail
{
public string displayName { get; set; }
public int totalCount { get; set; }
public int productID { get; set; }
public string imageURL { get; set; }
public string productTitle { get; set; }
public string digitialRiverID { get; set; }
public string productSKU { get; set; }
public string productUPC { get; set; }
public string productUPCOriginal { get; set; }
public string productPrice { get; set; }
public bool productAvailable { get; set; }
public object productRating { get; set; }
public object customerReviewCount { get; set; }
public bool isFounderEdition { get; set; }
public bool isFeaturedProduct { get; set; }
public bool certified { get; set; }
public string manufacturer { get; set; }
public string locale { get; set; }
public bool isFeaturedProdcutFoundInSecondSearch { get; set; }
public string category { get; set; }
public string gpu { get; set; }
public string purchaseOption { get; set; }
public string prdStatus { get; set; }
public object minShipDays { get; set; }
public object maxShipDays { get; set; }
public object shipInfo { get; set; }
public bool isOffer { get; set; }
public string offerText { get; set; }
public List<Retailer> retailers { get; set; }
public List<ProductInfo> productInfo { get; set; }
public List<CompareProductInfo> compareProductInfo { get; set; }
}
public class SearchedProducts
{
public int totalProducts { get; set; }
public bool featuredProductIncludedInCount { get; set; }
public bool featuredProductsFlag { get; set; }
public FeaturedProduct featuredProduct { get; set; }
public List<ProductDetail> productDetails { get; set; }
public List<object> suggestedProductDetails { get; set; }
}
public class Disclaimer
{
public string text { get; set; }
}
You can try the below code.
To get the Featured Product. Sample Working code Here
var jsonParse = JObject.Parse(json);
var featuredProduct = jsonParse["searchedProducts"]["featuredProduct"];
var f = new CarteGraphique
{
displayName = featuredProduct["displayName"].ToString(),
prdStatus = featuredProduct["prdStatus"].ToString(),
directPurchaseLink = featuredProduct["retailers"][0]["directPurchaseLink"].ToString()
};
Console.WriteLine("Featured Product Details : " + f.displayName + ", " + f.prdStatus + ", " + f.directPurchaseLink);
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.
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.
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.