简体   繁体   中英

Deserializing no array json object to dictionary in c#

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"
    }}}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM