簡體   English   中英

如何解析 json 對象,以便正確獲取所有值

[英]How do I parse json objects so that I can get all the values correctly

所以我得到了這個 JSON 字符串,它看起來像這樣:

{"success":false,"errors":[{"name":["Username "admin" has already been taken."],"email":["Email is not a valid email address."]}],"data":[]}

或者,更易讀:

{
  "success": false,
  "errors": [
    {
      "name": [
        "Username "admin" has already been taken."
      ],
      "email": [
        "Email is not a valid email address."
      ]
    }
  ],
  "data": []
}

而且我想以一種無論錯誤或值的名稱如何都可以獲取“錯誤”中的所有項目的方式對其進行解析。 因為“錯誤”中的對象並不總是“名稱”和“電子郵件”,所以可能會有不同的對象,但它們的結構總是如此。

我設法做到了這一點:

var theObject = (JObject)JsonConvert.DeserializeObject(theJsonString);

目標是把它變成一個字典,在那里我可以得到錯誤的名稱和值。 或者只是名稱和值作為一個字符串也可以。

基本上得到所有錯誤的集合。

更新

我嘗試將其反序列化為它自己的 object

var theObject = JsonConvert.DeserializeObject<ResponseObject>(responseString);

model 看起來像這樣

public class ResponseObject
{
    [JsonProperty("success")]
    public bool Success { get; set; }

    //[JsonProperty("errors")]
    //public Error[] Errors { get; set; }
    [JsonProperty("errors")]
    public Dictionary<string, List<string>> errors { get; set; }

    [JsonProperty("data")]
    public object[] Data { get; set; }
}

然后引發此錯誤

{"Cannot deserialize the current JSON array (eg [1,2,3]) into type 'System.Collections.Generic.Dictionary 2[System.String,System.Collections.Generic.List 1[System.String]]' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (eg {"name":"value"}) or將反序列化的類型更改為數組或實現集合接口(例如 ICollection、IList)的類型,例如可以從 JSON 數組反序列化的 List。也可以將 JsonArrayAttribute 添加到該類型以強制其從 Z0ECD11C1D7A287401D148A23BBD7A2F8 數組反序列化。 \r\n路徑“錯誤”,第 1 行,position 27。"}

錯誤是一個List<Dictionary<string, List<string>>>
它看起來像這樣:

"errors": [ <--
    {
      "1": [
        "Username &quot;admin&quot; has already been taken."
      ],
      "2": [
        "Email is not a valid email address."
      ]
    }
] <--
,

不是Dictionary<string, List<string>>會像:

"errors": 
    {
      "1": [
        "Username &quot;admin&quot; has already been taken."
      ],
      "2": [
        "Email is not a valid email address."
      ]
    },

一個簡單的解決方案是:

如果你有 Visual Studio 打開它。

  1. 復制你的 Json 代碼。
  2. 點擊它,它會自動為你生成你的代碼:)點擊這里

編輯 -> 導入 Json

祝你好運:,) 有時他可能會選擇“假”數據類型。 但是在你的小 json 上你會沒事的。

這將是 output:

public class Rootobject
    {
        public bool success { get; set; }
        public Error[] errors { get; set; }
        public object[] data { get; set; }
    }

    public class Error
    {
        public string[] name { get; set; }
        public string[] email { get; set; }
    }

暫無
暫無

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

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