簡體   English   中英

在C#中使用Newtonsoft反序列化JSON

[英]Deserializing JSON using Newtonsoft in C#

我有以下JSON:

[
    {
        "name": "codeURL",
        "value": "abcd"
    },
    {
        "name": "authURL",
        "value": "fghi"
    }
]

我創建了以下對象:

public class ConfigUrlModel {
    [JsonProperty("name")]
    public abstract string name { get; set; }
    [JsonProperty("value")]
    public abstract string value { get; set; }
}

public class ConfigUrlsModel {
    [JsonProperty]
    public List<ConfigUrlModel> ConfigUrls { get; set; }
}

我正在反序列化以下行:

resultObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ConfigUrlsModel>(resultString);
ConfigUrlsModel result = resultObject as ConfigUrlsModel;

我收到以下錯誤:

Exception JsonSerializationException with no inner exception: Cannot deserialize JSON array into type 'Microsoft.Xbox.Samples.Video.Services.Jtv.Models.ConfigUrl.ConfigUrlsModel'.
Exception JsonSerializationException with no inner exception: Cannot deserialize JSON array into type 'Microsoft.Xbox.Samples.Video.Services.Jtv.Models.ConfigUrl.ConfigUrlsModel'.
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(Type objectType, JsonContract contract)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contr   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(Type objectType, JsonContract contract)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contrNavigationService:OnNavigateToMessage PageSourceUri=/Microsoft.Xbox.Sample.UI;component/ErrorPrompt/ErrorPromptView.xaml

我究竟做錯了什么? 我該如何解決?

JSON根容器是一個數組,而不是一個對象,因此應將其反序列化:

var configUrls = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ConfigUrlModel>>(resultString);
var result = new ConfigUrlsModel { ConfigUrls = configUrls }; // If you still need the root object.

JSON數組是值[value1, value2, ..., value]的有序列表,這就是您的問題中顯示的內容。 Json.NET 會將.NET數組和集合轉換為JSON數組 ,因此您需要反序列化為集合類型。

您要發送的JSON是一個數組,但是您嘗試將其反序列化為一個對象。 以太更改JSON,使其與頂層的對象定義匹配,並具有匹配的屬性,如下所示:

{
   "ConfigUrls":[
      {
         "name":"codeURL",
         "value":"abcd"
      },
      {
         "name":"authURL",
         "value":"fghi"
      }
   ]
}

或將反序列化調用更改為:

var urls = DeserializeObject<List<ConfigUrlModel>>(json);

這將返回一個List<ConfigUrlModel> ,您可以直接使用它,也可以在需要時包裝在ConfigUrlModels實例中。

另外,可以通過創建自定義newtonsoft JsonConverter子類,將此JSON直接反序列化為所需的類。 但這會使代碼不太清晰,因此請盡可能避免使用。

暫無
暫無

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

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