簡體   English   中英

將無數組 json object 反序列化為 c# 中的字典

[英]Deserializing no array json object to dictionary in c#

我正在嘗試將 json 反序列化為 c# class。 我不確定如何將 ErrorContent 放入鍵值對字典中? 由於錯誤內容不是數組,我還可以將其轉換為字典嗎?

當我嘗試下面的代碼時,我不斷收到錯誤內容為 null..

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

class 搜索響應看起來像

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

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

樣品 json 看起來像

    {   
    "statusCode": 1233,   "status": "ERROR",   "payloadType": "ERROR", "payload": {
    "ErrorContent":{
       "101": "Value cannot be null",
       "102": "Value should always be integer"
    }}}

像這樣更改您的 model。 由於型號錯誤,您的 JSON 和 C# model 無法正確綁定

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

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

    }

裝訂步驟

  1. 首先,您的 model 將尋找SearchResponse class
  2. 然后它將尋找一個名為payload的 class
  3. 然后它將查找名稱為ErrorContent的字典

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM