-2

I am trying to deserilaize json to a c# class. I am not sure how I can get the ErrorContent into Dictionary of key value pair? Since Error Content is not an array, can I still convert it to Dictionary?

When I try below code, I keep getting ErrorContent as null..

    var response = JsonConvert.DeserializeObject<SearchResponse>(jsonResponse);

The class Search Response looks like

public class SearchResponse
{
    public ErrorContent Errors { get; set; }
}

public class ErrorContent
{
    public Dictionary<int, string> Errors { get; set; } = new Dictionary<int, string>();
} 

Sample json looks like

    {   
    "statusCode": 1233,   "status": "ERROR",   "payloadType": "ERROR", "payload": {
    "ErrorContent":{
       "101": "Value cannot be null",
       "102": "Value should always be integer"
    }}}
challengeAccepted
  • 7,106
  • 20
  • 74
  • 105
  • 1
    You're missing the `payload` property, of which `ErrorContent` is a child. It's also named `ErrorContent` in the JSON, so you likely want your C# property to be named the same. Use a service like https://jsonutils.com/ to convert your JSON to C# classes. – Heretic Monkey Jun 12 '20 at 20:35
  • 1
    Does this answer your question? [How can I deserialize JSON to a simple Dictionary in ASP.NET?](https://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net) – Heretic Monkey Jun 12 '20 at 20:36
  • You can decorate your model with correct JSON properties. Response contains `payload` property, which has `ErrorContent` that can be parsed to `Dictionary` – Pavel Anikhouski Jun 12 '20 at 20:38

1 Answers1

1

Change your model like this. Your JSON and C# model are not correctly binding due to wrong models

  public class SearchResponse
    {
        [JsonProperty("payload")]
        public PayLoad PayLoad { get; set; }
    }

    public class PayLoad
    {
        public Dictionary<int, string> ErrorContent { get; set; }

    }

Binding Steps

  1. First your model will look for SearchResponse class
  2. Then it will look for a class named payload
  3. Then it will look for a dictionary with name ErrorContent
Hammad Shabbir
  • 722
  • 1
  • 6
  • 13