【发布时间】:2018-10-12 14:31:45
【问题描述】:
我有以下 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\n路径 '',第 1 行,位置 1."}Newtonsoft.Json.JsonSerializationException
我还需要序列化什么?
【问题讨论】: