我有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"
}
}
]
Run Code Online (Sandbox Code Playgroud)
以下是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; }
}
Run Code Online (Sandbox Code Playgroud)
现在尝试加载JSON并获得低于错误,
using (var streamReader = new StreamReader(@"./Config.json"))
{
var X = JsonConvert.DeserializeObject<Configurations>(streamReader.ReadToEnd());
}
Run Code Online (Sandbox Code Playgroud)
$ exception {"无法将当前JSON数组(例如[1,2,3])反序列化为'ConsoleApp8.Configurations'类型,因为该类型需要一个JSON对象(例如{\"name \":\"value \"})正确反序列化.\ r \n要修复此错误,请将JSON更改为JSON对象(例如{\"name \":\"value \"})或将反序列化类型更改为数组或实现集合的类型接口(例如ICollection,IList),如List,可以从JSON数组反序列化.JsonArrayAttribute也可以添加到类型中,以强制它从JSON数组反序列化.\ r \n路由'',第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
Run Code Online (Sandbox Code Playgroud)
然后使用:
List<Configuration> configurations =
JsonConvert.DeserializeObject<List<Configuration>>(streamReader.ReadToEnd());
Run Code Online (Sandbox Code Playgroud)
然后,您将拥有一个配置对象列表,每个配置对象都有三个"子配置"部分.
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |