首页 > 解决方案 > 加载 JSON 文件会导致序列化错误

问题描述

我有以下 JSON 文件,

[
  {
    "applicationConfig": {
      "Name": "Name1",
      "Site": "Site1"
    },
    "pathConfig": {
      "SourcePath": "C:\\Temp\\Outgoing1",
      "TargetPath": "C:\\Files"
    },
    "credentialConfig": {
      "Username": "test1",
      "password": "super1"
    }
  },
  {
    "applicationConfig": {
      "Name": "Name2",
      "Site": "Site2"
    },
    "pathConfig": {
      "SourcePath": "C:\\Temp\\Outgoing2",
      "TargetPath": "C:\\Files"
    },
    "credentialConfig": {
      "Username": "test2",
      "password": "super2"
    }
  }
]

下面是 C# 类结构,

public class Configurations
{
    public List<ApplicationConfig> ApplicationConfigs { get; set; }
    public List<PathConfig> PathConfigs { get; set; }
    public List<CredentialConfig> CredentialConfigs { get; set; }
}


public class ApplicationConfig
{
    public string Name { get; set; }
    public string Site { get; set; }
}

public class PathConfig
{
    public string SourcePath { get; set; }
    public string TargetPath { get; set; }
}

public class CredentialConfig
{
    public string Username { get; set; }
    public string password { get; set; }
}

现在尝试加载 JSON 并低于错误,

using (var streamReader = new StreamReader(@"./Config.json"))
        {
           var X = JsonConvert.DeserializeObject<Configurations>(streamReader.ReadToEnd());
        }

$exception {"无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'ConsoleApp8.Configurations',因为该类型需要 JSON 对象(例如 {\"name\":\"value\"})正确反序列化。\r\n要修复此错误,请将 JSON 更改为 JSON 对象(例如 {\"name\":\"value\"})或将反序列化的类型更改为数组或实现集合的类型接口(例如 ICollection、IList),例如可以从 JSON 数组反序列化的 List。也可以将 JsonArrayAttribute 添加到类型中以强制它从 JSON 数组反序列化。\r\nPath '',第 1 行,第 1 位。" } Newtonsoft.Json.JsonSerializationException

我还需要序列化什么?

标签: c#json

解决方案


您的 JSON 代表一个数组 - 尽管结束[应该是]. 但是您正在尝试将其序列化为单个Configurations对象。此外,您似乎期望应用程序配置、路径配置和凭证配置的单独数组 - 而您的 JSON 显示一个对象数组,每个对象都包含这三个。

我怀疑你想要:

public class Configuration
{
    [JsonProperty("applicationConfig")]
    ApplicationConfig ApplicationConfig { get; set; }

    [JsonProperty("pathConfig")]
    PathConfig PathConfig { get; set; }

    [JsonProperty("credentialConfig")]
    CredentialConfig CredentialConfig { get; set; }
}

// Other classes as before, although preferably with the password property more conventionally named

然后使用:

List<Configuration> configurations = 
    JsonConvert.DeserializeObject<List<Configuration>>(streamReader.ReadToEnd());

然后,您将获得一个配置对象列表,每个对象都包含三个“子配置”部分。


推荐阅读