I have a JSON object with a dynamic key for the properties I wish to map to a class. I'm uncertain how to build my class to deserialize with JSON.NET. I need the values from the 'results' and 'more' keys at the upper level and also the the values from the 'timesheets' key.
Here is my JSON data.
{
"results": {
"timesheets": {
"7994790": {
"id": 7994790,
"user_id": 165502,
"jobcode_id": 11267673,
"start": "2019-12-20T05:48:00-05:00",
"end": "2019-12-20T13:44:00-05:00",
"duration": 28560,
"date": "2019-12-20",
"tz": -5,
"tz_str": "tsET",
"type": "regular",
"location": "Android App",
"on_the_clock": false,
"locked": 0,
"notes": "",
"customfields": {
"20251": "",
"19647": "Laborer",
"20327": "",
"19648": ""
},
"last_modified": "2019-12-20T20:28:48+00:00",
"attached_files": [],
"created_by_user_id": 165502
},
"8087496": {
"id": 8087496,
"user_id": 165502,
"jobcode_id": 2415904,
"start": "2019-12-20T13:44:00-05:00",
"end": "2019-12-20T15:11:00-05:00",
"duration": 5220,
"date": "2019-12-20",
"tz": -5,
"tz_str": "tsET",
"type": "regular",
"location": "Android App",
"on_the_clock": false,
"locked": 0,
"notes": "",
"customfields": {
"20251": "",
"19647": "Laborer",
"20327": "",
"19648": ""
},
"last_modified": "2019-12-20T20:28:49+00:00",
"attached_files": [],
"created_by_user_id": 165502
}
}
},
"more": false
}
And my classes as I currently have them which returns this error.
System.ArgumentNullException: 'Value cannot be null.
Parameter name: values'
public class RootObject
{
public Results results { get; set; }
public bool more { get; set; }
}
public class Results
{
public Timesheets timesheets { get; set; }
}
public class Timesheets
{
public Dictionary<int, TimesheetDetails> timesheetsdetails { get; set; }
}
public class TimesheetDetails
{
public int id { get; set; }
public int user_id { get; set; }
public int jobcode_id { get; set; }
public DateTime start { get; set; }
public DateTime end { get; set; }
public int duration { get; set; }
public string date { get; set; }
public int tz { get; set; }
public string tz_str { get; set; }
public string type { get; set; }
public string location { get; set; }
public bool on_the_clock { get; set; }
public int locked { get; set; }
public string notes { get; set; }
public DateTime last_modified { get; set; }
public List<object> attached_files { get; set; }
public int created_by_user_id { get; set; }
}
var stuff = JsonConvert.DeserializeObject<RootObject>(result.Content);
Console.WriteLine(string.Join(",", stuff.results.timesheets.timesheetsdetails));
First of all your json is not valid. After the end of the first timesheet data, there should be a , You can use any json validator online simply to validate it.
And in your model the Results is not valid according to the json. The below one works for me.
public class Response
{
[JsonProperty("results")] public TimeSheetResponse TimeSheetResponse { get; set; }
[JsonProperty("more")] public bool More { get; set; }
}
public class TimeSheetResponse
{
[JsonProperty("timesheets")] public Dictionary<string, Timesheet> Timesheets { get; set; }
}
public class Timesheet
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("user_id")]
public long UserId { get; set; }
[JsonProperty("jobcode_id")]
public long JobcodeId { get; set; }
[JsonProperty("start")] public DateTimeOffset Start { get; set; }
[JsonProperty("end")] public DateTimeOffset End { get; set; }
[JsonProperty("duration")] public long Duration { get; set; }
[JsonProperty("date")] public DateTimeOffset Date { get; set; }
[JsonProperty("tz")] public long Tz { get; set; }
[JsonProperty("tz_str")] public string TzStr { get; set; }
[JsonProperty("type")] public string Type { get; set; }
[JsonProperty("location")] public string Location { get; set; }
[JsonProperty("on_the_clock")] public bool OnTheClock { get; set; }
[JsonProperty("locked")] public long Locked { get; set; }
[JsonProperty("notes")] public string Notes { get; set; }
[JsonProperty("customfields")] public Dictionary<string, string> Customfields { get; set; }
[JsonProperty("last_modified")] public DateTimeOffset LastModified { get; set; }
[JsonProperty("attached_files")] public List<object> AttachedFiles { get; set; }
[JsonProperty("created_by_user_id")]
public long CreatedByUserId { get; set; }
}
To deserialize to Object..
var timeSheetResult = JsonConvert.DeserializeObject<Response>(data);
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.
I have a json data as below -
{
"request": {
"type": "",
"query": "",
"language": "en",
"unit": "m"
},
"location": {
"name": "",
"country": "",
"region": "",
"lat": "",
"lon": "",
"timezone_id": "Asia/Kolkata",
"localtime": "2020-05-29 23:30",
"localtime_epoch": 1590795000,
"utc_offset": "5.50"
},
"current": {
"observation_time": "06:00 PM",
"temperature": 40,
"weather_code": 116,
"weather_icons": [
""
],
"weather_descriptions": [
"Partly cloudy"
],
"wind_speed": 9,
"wind_degree": 230,
"wind_dir": "SW",
"pressure": 1006,
"precip": 0,
"humidity": 26,
"cloudcover": 25,
"feelslike": 42,
"uv_index": 1,
"visibility": 6,
"is_day": "no"
},
"forecast": {
"2020-05-28": {
"date": "2020-05-28",
"date_epoch": 1590624000,
"astro": {
"sunrise": "05:41 AM",
"sunset": "06:46 PM",
"moonrise": "10:29 AM",
"moonset": "11:48 PM",
"moon_phase": "First Quarter",
"moon_illumination": 39
},
"mintemp": 32,
"maxtemp": 44,
"avgtemp": 38,
"totalsnow": 0,
"sunhour": 13.1,
"uv_index": 9
}
}
}
First Three nodes("request","location","current") are binding properly but for "forecast" since the first node is a date time. I have written in the following way-
var dataObjects = JsonConvert.DeserializeObject<Location_Weather.Weather>(customerJsonString);
var dataObjects23 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>> (customerJsonString);
dynamic forecast_details = dataObjects23["forecast"];
This is my Model->
public class New_Location_Weather
{
[JsonProperty("request")]
public Request Request { get; set; }
[JsonProperty("location")]
public Location Location { get; set; }
[JsonProperty("current")]
public Current Current { get; set; }
[JsonProperty("forecast")]
public Forecast Forecast { get; set; }
}
public partial class Current
{
[JsonProperty("observation_time")]
public string ObservationTime { get; set; }
[JsonProperty("temperature")]
public long Temperature { get; set; }
[JsonProperty("weather_code")]
public long WeatherCode { get; set; }
[JsonProperty("weather_icons")]
public Uri[] WeatherIcons { get; set; }
[JsonProperty("weather_descriptions")]
public string[] WeatherDescriptions { get; set; }
[JsonProperty("wind_speed")]
public long WindSpeed { get; set; }
[JsonProperty("wind_degree")]
public long WindDegree { get; set; }
[JsonProperty("wind_dir")]
public string WindDir { get; set; }
[JsonProperty("pressure")]
public long Pressure { get; set; }
[JsonProperty("precip")]
public long Precip { get; set; }
[JsonProperty("humidity")]
public long Humidity { get; set; }
[JsonProperty("cloudcover")]
public long Cloudcover { get; set; }
[JsonProperty("feelslike")]
public long Feelslike { get; set; }
[JsonProperty("uv_index")]
public long UvIndex { get; set; }
[JsonProperty("visibility")]
public long Visibility { get; set; }
[JsonProperty("is_day")]
public string IsDay { get; set; }
}
public partial class Forecast
{
[JsonProperty("2020-05-28")]
public The20200528 The20200528 { get; set; }
}
public partial class The20200528
{
[JsonProperty("date")]
public DateTimeOffset Date { get; set; }
[JsonProperty("date_epoch")]
public long DateEpoch { get; set; }
[JsonProperty("astro")]
public Astro Astro { get; set; }
[JsonProperty("mintemp")]
public long Mintemp { get; set; }
[JsonProperty("maxtemp")]
public long Maxtemp { get; set; }
[JsonProperty("avgtemp")]
public long Avgtemp { get; set; }
[JsonProperty("totalsnow")]
public long Totalsnow { get; set; }
[JsonProperty("sunhour")]
public double Sunhour { get; set; }
[JsonProperty("uv_index")]
public long UvIndex { get; set; }
}
public partial class Astro
{
[JsonProperty("sunrise")]
public string Sunrise { get; set; }
[JsonProperty("sunset")]
public string Sunset { get; set; }
[JsonProperty("moonrise")]
public string Moonrise { get; set; }
[JsonProperty("moonset")]
public string Moonset { get; set; }
[JsonProperty("moon_phase")]
public string MoonPhase { get; set; }
[JsonProperty("moon_illumination")]
public long MoonIllumination { get; set; }
}
public partial class Location
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("region")]
public string Region { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
[JsonProperty("lon")]
public string Lon { get; set; }
[JsonProperty("timezone_id")]
public string TimezoneId { get; set; }
[JsonProperty("localtime")]
public string Localtime { get; set; }
[JsonProperty("localtime_epoch")]
public long LocaltimeEpoch { get; set; }
[JsonProperty("utc_offset")]
public string UtcOffset { get; set; }
}
public partial class Request
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("query")]
public string Query { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("unit")]
public string Unit { get; set; }
}
Now issue is I am not able to get the values. I need some guidance on how to get this values from the dynamic object which is forecast_details into my C# code.
Below is the screenshot of the values which I need to access them in my c# code
While debugging the dynamic object I found the values in my result view. But I am not sure how to access those values in my c# code.
Please do let me know on how to get these values from my C# dynamic object(forecast_details).
Look at this question, there is two answers that can help you.
How to add properties at runtime to JSON (C#)
You can parse your forecast json to JObject, and get all values from it with foreach.
This is what I figured it out. Hope it helps for others to.
JObject obj = JObject.Parse(customerJsonString);
var forecast_details = obj.SelectToken("forecast").Children().OfType<JProperty>()
.ToDictionary(p => p.Name, p => new
{
MaxTemp = (int)p.First()["maxtemp"],
MinTemp = (int)p.First()["mintemp"]
});
if(forecast_details.Count>0)
{
int max_temp = forecast_details.Values.Select(x => x.MaxTemp).FirstOrDefault();
int min_temp = forecast_details.Values.Select(x => x.MinTemp).FirstOrDefault();
}
I have this Json:
{
"trades": [
{
"id": "4004",
"instrument": "EUR_USD",
"price": "1.08938",
"openTime": "2020-02-26T12:15:32.309973340Z",
"initialUnits": "1",
"initialMarginRequired": "0.0363",
"state": "OPEN",
"currentUnits": "1",
"realizedPL": "0.0000",
"financing": "0.0000",
"dividendAdjustment": "0.0000",
"unrealizedPL": "-0.0026",
"marginUsed": "0.0362",
"takeProfitOrder": {
"id": "4005",
"createTime": "2020-02-26T12:15:32.309973340Z",
"type": "TAKE_PROFIT",
"tradeID": "4004",
"price": "1.09099",
"timeInForce": "GTC",
"triggerCondition": "DEFAULT",
"state": "PENDING"
}
}
],
"lastTransactionID": "4010"
}
And Classes:
public class TakeProfitOrder
{
public string id { get; set; }
public string createTime { get; set; }
public string type { get; set; }
public string tradeID { get; set; }
public string price { get; set; }
public string timeInForce { get; set; }
public string triggerCondition { get; set; }
public string state { get; set; }
}
public class Trade
{
public string id { get; set; }
public string instrument { get; set; }
public string price { get; set; }
public string openTime { get; set; }
public string initialUnits { get; set; }
public string initialMarginRequired { get; set; }
public string state { get; set; }
public string currentUnits { get; set; }
public string realizedPL { get; set; }
public string financing { get; set; }
public string dividendAdjustment { get; set; }
public string unrealizedPL { get; set; }
public string marginUsed { get; set; }
public TakeProfitOrder takeProfitOrder { get; set; }
}
public class RootObject
{
public List<Trade> trades { get; set; }
public string lastTransactionID { get; set; }
}
I deserialize with :
var result = JsonConvert.DeserializeObject<RootObject>(Json);
var price = result.trades.Select(p => p.price).ToList();
price.ForEach(Console.WriteLine);
It works. I can access "price" in "trades", but I do not know how to access the "price" in "takeProfitOrder". I need the value of "price" from "takeProfitOrder" in to a list. I am sure it is something very simple but I cannot figure out how to do it, even after looking at some similar examples.
Can somebody please help me?
It's simple
result.trades.Select(p => p.takeProfitOrder.price)
You should understand better from this example
foreach (Trade trade in result.trades)
{
TakeProfitOrder takeProfitOrder = trade.takeProfitOrder;
Console.WriteLine(takeProfitOrder.price);
}
How can I convert my json-string to class
this is my json
{
"$id": "1",
"Result": {
"$id": "2",
"dateTime": 23821964,
"list": [{
"$id": "3",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false,
"ForfeitCount": 0,
"RewardCount": 0,
"ThisCountReport": 2,
"Reported": [{
"$id": "4",
"BlockerId": 355,
"Title": "محتوای غیر اخلاقی",
"Date": -19527396,
"ForfeitCount": 0,
"RewardCount": 0
}, {
"$id": "5",
"BlockerId": 355,
"Title": "محتوای غیر مرتبط",
"Date": -19527382,
"ForfeitCount": 0,
"RewardCount": 0
}],
"Gem": 0
}, {
"$id": "6",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false
}]
},
"StatusCode": "Created",
"Description": null
}
And I do these step, but nothing happens
JObject json1 = JObject.Parse(strMyJson);
_CommentAdmindto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<_CommentAdmindto>(json1.ToString());
_CommentAdmindto deserializedProduct = JsonConvert.DeserializeObject<_CommentAdmindto>(json);
_CommentAdmindto deserializedProduct1 = ConvertJsonToClass<_CommentAdmindto>(strMyJson);
JsonSerializer serializer = new JsonSerializer();
_CommentAdmindto p = (_CommentAdmindto)serializer.Deserialize(new JTokenReader(strMyJson), typeof(_CommentAdmindto));
And here is my class and function:
public static T ConvertJsonToClass<T>( string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IQueryable<CommentDtoAdmin> list { get; set; }
}
public class CommentDtoAdmin
{
public long UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public string ProductTitle { get; set; }
public long CommentId { get; set; }
public string Logo { get; set; }
public long Date { get; set; }
public long AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
}
Your model should be similar to this (For invalid c# names, you can use JsonProperty attribute) :
public class Reported
{
[JsonProperty("$id")]
public string id { get; set; }
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class List
{
[JsonProperty("$id")]
public string id { get; set; }
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
[JsonProperty("$id")]
public string id { get; set; }
public int dateTime { get; set; }
public List<List> list { get; set; }
}
public class RootObject
{
[JsonProperty("$id")]
public string id { get; set; }
public Result Result { get; set; }
public string StatusCode { get; set; }
public object Description { get; set; }
}
Now you can deserialize as
var result = JsonConvert.DeserializeObject<RootObject>(jsonstring);
BTW: http://json2csharp.com/ can help to guess your model when working with json.
You seem to be trying to deserialize in a lot of different ways but you don't have a full structure to actually match the json. You miss the outer class (representing the full object) and at least Newtonsoft.Json cannot deserialize to an IQueryable so I changed that to IEnumerable.
string strMyJson = "{\"$id\":\"1\",\"Result\":{\"$id\":\"2\",\"dateTime\":23826985,\"list\":[{\"$id\":\"3\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false,\"ForfeitCount\":0,\"RewardCount\":0,\"ThisCountReport\":2,\"Reported\":[{\"$id\":\"4\",\"BlockerId\":355,\"Title\":\"Ù…Øتوای غیر اخلاقی\",\"Date\":-19527396,\"ForfeitCount\":0,\"RewardCount\":0},{\"$id\":\"5\",\"BlockerId\":355,\"Title\":\"Ù…Øتوای غیر مرتبط\",\"Date\":-19527382,\"ForfeitCount\":0,\"RewardCount\":0}],\"Gem\":0},{\"$id\":\"6\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false}],\"StatusCode\":\"Created\",\"Description\":null}}";
var result = JsonConvert.DeserializeObject<Wrapper>(strMyJson);
with classes looking like this:
public class Wrapper
{
public _CommentAdmindto Result { get; set; }
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IEnumerable<CommentDtoAdmin> list { get; set; }
}
CommentDtoAdmin is looking the same.
Though I must say that this only helps you with the deserialization.
Firstly, the $id" properties are synthetic properties added by Json.NET to track and preserve multiple references to the same object. For details, see PreserveReferencesHandling setting.
Thus, if you temporarily remove the "$id" properties, you can upload your JSON to http://json2csharp.com/ and get the following data model:
public class Reported
{
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class CommentDtoAdmin
{
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
public int dateTime { get; set; }
public List<CommentDtoAdmin> list { get; set; }
}
public class RootObject
{
public Result Result { get; set; }
public string StatusCode { get; set; }
public string Description { get; set; }
}
I then modified the returned model as follows:
I used the name CommentDtoAdmin for the list type.
I set the type of the Description property to string.
Now your JSON can be deserialized and re-serialized as follows:
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var root = JsonConvert.DeserializeObject<RootObject>(json1, settings);
var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);
Note that Json.NET has no built-in logic for deserializing the interface IQueryable<T> to a concrete type, so I had to leave the property as public List<CommentDtoAdmin> list { get; set; }. You can always generate a queryable from the list using AsQueryable():
var queryable = root.Result.list.AsQueryable();
Sample fiddle.
I think you json string does not have correct syntax. It looks like a ']' (end of Array) and a final '}' is missing.
That's what the Visual Studio editor told me when making a json file out of your string after removing all the '\'
How can I De-serialize following json?
{
"data": {
"11396": {
"description": "Timer project",
"status": "ACTIVE",
"customer": {
"locations": {},
"id": 96626
},
"tasks": [
{
"description": "Timer Task",
"unit": "h",
"vatPct": 0.2,
"unitPrice": 12,
"billable": true,
"id": 19660
}
],
"price": 0,
"pricing": "UNIT",
"allowProducts": true,
"hasUninvoicedItems": false,
"id": 11396
},
"11397": {
"description": "Timer Project 2",
"status": "ACTIVE",
"customer": {
"locations": {},
"id": 96626
},
"tasks": [
{
"description": "Timer Task2",
"unit": "h",
"vatPct": 0.05,
"unitPrice": 20,
"billable": true,
"id": 19655
}
],
"price": 0,
"pricing": "UNIT",
"allowProducts": true,
"hasUninvoicedItems": false,
"id": 11397
}
},
"ok": true
}
The problem is that values 11396, 11397 as class name (if convert to c#) which are actually ids of that particular record. so when converting this json to c# using http://json2csharp.com. it shows as this
public class Locations
{
}
public class Customer
{
public Locations locations { get; set; }
public int id { get; set; }
}
public class Task
{
public string description { get; set; }
public string unit { get; set; }
public double vatPct { get; set; }
public double unitPrice { get; set; }
public bool billable { get; set; }
public int id { get; set; }
}
public class __invalid_type__11397
{
public string description { get; set; }
public string status { get; set; }
public Customer customer { get; set; }
public List<Task> tasks { get; set; }
public double price { get; set; }
public string pricing { get; set; }
public bool allowProducts { get; set; }
public bool hasUninvoicedItems { get; set; }
public int id { get; set; }
}
public class Locations2
{
}
public class Customer2
{
public Locations2 locations { get; set; }
public int id { get; set; }
}
public class Task2
{
public string description { get; set; }
public string unit { get; set; }
public double vatPct { get; set; }
public double unitPrice { get; set; }
public bool billable { get; set; }
public int id { get; set; }
}
public class __invalid_type__11396
{
public string description { get; set; }
public string status { get; set; }
public Customer2 customer { get; set; }
public List<Task2> tasks { get; set; }
public double price { get; set; }
public string pricing { get; set; }
public bool allowProducts { get; set; }
public bool hasUninvoicedItems { get; set; }
public int id { get; set; }
}
public class Data
{
public __invalid_type__11397 __invalid_name__11397 { get; set; }
public __invalid_type__11396 __invalid_name__11396 { get; set; }
}
public class RootObject
{
public Data data { get; set; }
public bool ok { get; set; }
}
any help is much appreciated.
I resolved this issue by parsing the json string to JTOKEN and the querying the required data.
This was possible because my datas inside json was static
JToken token = JObject.Parse(response);
var justDaily = token["data"];
ProjectList = new List<Project>();
foreach (JToken child in justDaily.Children())
{
foreach (JToken grandChild in child)
{
Project temp = JsonConvert.DeserializeObject<Project>(grandChild.ToString().Replace("\r\n", ""));
ProjectList.Add(temp);
}
}
Hope this will help someone else also