c# - 加载 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
我还需要序列化什么?
解决方案
您的 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());
然后,您将获得一个配置对象列表,每个对象都包含三个“子配置”部分。
推荐阅读
- javascript - 动态地将类添加到 React map 函数中的前 n 个元素
- mysql - 我需要通过以下方式加入这两个表..使用mysql
- prismjs - 如何在 Scully 中突出显示代码块?
- axon - Axon Saga 订阅模式并发问题
- kubernetes - 嗨,我正在尝试让客户端 real-ip 限制 kubernetes 环境上 pod 的某些访问
- docker - 如何从运行在同一 Kubernetes 集群中的容器连接到在 Kubernetes 集群中的主机 VM 上运行的 Docker?
- python - Micropython构建外部C模块
- android - 如何观察更改对象 Kotlin
- java - 如何从用户输入中获取随机字符并将随机字符存储到数组中?
- firebase - 将 Firebase Cloud Functions 用作 API 时的计费问题