【发布时间】:2016-06-29 23:51:23
【问题描述】:
提前感谢您的帮助。
我有一个包含嵌套对象列表的 JSON 文件。使用下面的代码 - 我在调用 DeserializeObject 时遇到异常。我们正在使用 JSON.net
感谢任何帮助
JSON:
[
{
"Email": "james@example.com",
"Active": true,
"CreatedDate": "2013-01-20T00:00:00Z",
"Input": {
"User": "Jim",
"Admin": "John"
},
"Output": {
"Version": "12345",
"Nylon": "None"
}
},
{
"Email": "bob@example.com",
"Active": true,
"CreatedDate": "2013-01-21T00:00:00Z",
"Input": {
"User": "Bob",
"Admin": "John"
},
"Output": {
"Version": "12399",
"Nylon": "134"
}
}
]
为了支持反序列化,我创建了以下类结构。
public class Test002
{
public class Input
{
public string User { get; set; }
public string Admin { get; set; }
}
public class Output
{
public string Version { get; set; }
public string Nylon { get; set; }
}
public class RootObject
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public Input input { get; set; }
public Output output { get; set; }
}
public class TestCases
{
public List<RootObject> rootObjects { get; set; }
}
}
最后是对 JSON.net JsonConvert.DeserializeObject 的调用 - 引发以下异常。
Test002.TestCases tTestCases = JsonConvert.DeserializeObject<Test002.TestCases>(File.ReadAllText(@"C:\test\Automation\API\Test002.json"));
我想我需要这样的东西 - 反序列化对象列表 - 下面的代码失败
Test002.TestCases tTestCases = JsonConvert.DeserializeObject<IList<Test002.TestCases>>(File.ReadAllText(@"C:\test\Automation\API\Test002.json"));
例外:
Newtonsoft.Json.dll 中出现“Newtonsoft.Json.JsonSerializationException”类型的异常,但未在用户代码中处理
附加信息:无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'APISolution.Test002+TestCases',因为该类型需要 JSON 对象(例如 {"name":"value"})正确反序列化。
要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化的列表。也可以将 JsonArrayAttribute 添加到类型中以强制它从 JSON 数组中反序列化。
路径'',第 1 行,位置 1。
【问题讨论】:
-
你不需要
TestCases类。它应该反序列化为一个 RootObject 对象,其中包含里面的东西
标签: c# arrays json serialization