【发布时间】:2018-12-12 09:37:09
【问题描述】:
下面是一个Json:
[{
"Result": {
"description": "Application Security Supp Specialist",
"code": "40000003"
}
}, {
"Result": {
"description": "Gvt Cyber Intelligence Specialist",
"code": "40001416"
}
}, {
"Result": {
"description": "Gvt Record Retention Specialist",
"code": "40001428"
}
}]
下面是我创建的类结构,因为我需要将其填充到 C# 对象中。 我正在尝试创建 RulesEngineOutput 的集合并用 json 内容填充它。
public class RulesEngineOutput
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
}
public class RulesEngineOutputCollection
{
public IEnumerable<RulesEngineOutput> ProbableRoles { get; set; }
}
我正在尝试使用以下代码实现此目的:
var bodyJson = JsonConvert.SerializeObject(bodyString);
RulesEngineOutputCollection result = new RulesEngineOutputCollection();
foreach (var item in bodyJson)
{
result = JsonConvert.DeserializeObject<RulesEngineOutputCollection>(item.ToString());
}
但是当项目获得一个字符时,这会引发异常,我认为我需要在循环中传递一个 JSON 对象,但我无法得到一个。 每次我得到的是一个 JSON 字符串。
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“RulesEngineOutputCollection”,因为该类型需要 JSON 对象(例如 {\"name\":\"value\"})才能正确反序列化.\r\n要修复此错误,请将 JSON 更改为 JSON 对象(例如 {\"name\":\"value\"})或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection, IList) 之类的可以从 JSON 数组反序列化的 List。
【问题讨论】:
-
请发布您的错误消息的确切措辞。指定引发异常的代码行。
-
ProbableRoles应该被称为(或有JsonProperty)“结果” -
是的,您的 DTO 看起来不太正确。您可以将您的 JSON 插入 json2csharp.com 进行验证。
-
等等。
bodyString是什么?从它的声音来看,这包含您的 JSON。为什么要连载它?然后尝试遍历那个字符串?? -
Robert -- 这是我收到的错误消息
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RulesEngineOutputCollection' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array.
标签: c# .net json json.net jobjectformatter