2015-10-05 92 views
1

我有以下的JSON:反序列化JSON在C#中使用Newtonsoft

[ 
    { 
     "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 

我在做什麼錯?我該如何解決?

+0

其中是JtvConfigUrlsModel ?? – 2015-10-05 07:32:28

+0

@PranavPatel Jtv是一個錯誤。它是ConfigUrlsModel。 – khateeb

回答

5

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 will convert .NET arrays and collections to JSON arrays,所以你需要反序列化到一個集合類型。

2

您要發送的JSON是一個數組,但您試圖將其反序列化爲一個對象。醚改變你的JSON所以它在頂層的對象確定指標相匹配,並具有匹配的屬性,就像這樣:

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

或更改反序列化調用:

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

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

此外,可以通過創建一個custom newtonsoft JsonConverter sublcass將此JSON直接反序列化到所需的類。但是這會讓代碼不那麼清晰,所以儘可能避免使用它。

相關問題