c#中使用Newtonsoft反序列化JSON

本文关键字:反序列化 JSON Newtonsoft | 更新日期: 2023-09-27 18:15:56

我有以下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

我做错了什么?我该如何解决这个问题?

c#中使用Newtonsoft反序列化JSON

根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直接反序列化到所需的类。但是这会让代码变得不那么清晰,所以尽量避免。