Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display JSON data (nested) in C#

I am fetching an API that returns a JSON response like this:

{
"id": 161635,
"rev": 1,
"fields": {
  "System.Url": "http://google.com",
  "System.Type": "Bug",
  "System.State": "New",
  "System.AssignedTo": {
    "displayName": "John Doe"
    }
  }
}

I want to display the id and everything inside fields.
This is my model:

public class WorkItemDetail {
  public int id { get; set; }
  public Dictionary<string, object> fields {get;set;}
}

Here is the problem, I can display the id and everything in fields except for some reason, I can’t show displayName

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is what I doing:

@WorkItemDetailResponse.id
@WorkItemDetailResponse.fields["System.WorkItemType"];  
@WorkItemDetailResponse.fields["System.State"]; 
@WorkItemDetailResponse.fields["System.AssignedTo"]; 
@WorkItemDetailResponse.fields["System.AssignedTo"]["displayName"]; <!-- does not work -->


@code{
 WorkItemDetailResponse = JsonConvert.DeserializeObject<WorkItemDetail>(ResponseBody); 
}

I am new to C# so I don’t know why this line is not working

@WorkItemDetailResponse.fields["System.AssignedTo"]["displayName"]

>Solution :

Create your DTO structure as follows:

public class Fields
{
    [JsonProperty("System.Url")]
    public string SystemUrl { get; set; }

    [JsonProperty("System.Type")]
    public string SystemType { get; set; }

    [JsonProperty("System.State")]
    public string SystemState { get; set; }

    [JsonProperty("System.AssignedTo")]
    public SystemAssignedTo SystemAssignedTo { get; set; }
}

public class WorkItemDetail
{
    public int id { get; set; }
    public int rev { get; set; }
    public Fields fields { get; set; }
}

public class SystemAssignedTo
{
    public string displayName { get; set; }
}

here’s fiddle: https://dotnetfiddle.net/F9Wppv

another way – using dynamic variable: https://dotnetfiddle.net/Goh7YY

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading