2

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

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"]
1
  • You have to create each class for every nested json Commented Jun 29, 2022 at 12:19

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, it works and I understand how to do it for other fields.
you can auto generate this structure from json: json2csharp.com
2

You need to cast the object value to a JObject

((JObject)JsonConvert.DeserializeObject<WorkItemDetail>(json).fields["System.AssignedTo"])["displayName"]

JSON.Net will create a JObject if the property type is object and the value is a JSON object.

db<>fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.