我有这个JSON:
[
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 1",
"Values": [
"Acc 1"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "1",
"Values": [
"1"
]
}
}
],
"Name": "account",
"Id": "1"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 2",
"Values": [
"Acc 2"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "2",
"Values": [
"2"
]
}
}
],
"Name": "account",
"Id": "2"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 3",
"Values": [
"Acc 3"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "3",
"Values": [
"3"
]
}
}
],
"Name": "account",
"Id": "2"
}
]
我有这些类:
public class RetrieveMultipleResponse
{
public List<Attribute> Attributes { get; set; }
public string Name { get; set; }
public string Id { get; set; }
}
public class Value
{
[JsonProperty("Value")]
public string value { get; set; }
public List<string> Values { get; set; }
}
public class Attribute
{
public string Key { get; set; }
public Value Value { get; set; }
}
我正在尝试使用下面的代码反序列化上面的JSON:
var objResponse1 = JsonConvert.DeserializeObject<RetrieveMultipleResponse>(JsonStr);
但我得到了这个错误:
无法将当前JSON数组(例如[1,2,3])反序列化为类型“Test.Model.RetrieveMultipleResponse”,因为该类型需要一个JSON对象(例如{“name”:“value”})才能正确反序列化.要修复此错误,可以将JSON更改为JSON对象(例如{“name”:“value”}),或者将反序列化类型更改为数组或实现集合接口(例如ICollection、IList)的类型,该集合接口可以从JSON数组反序列化。还可以将JsonArrayAttribute添加到类型中,以强制它从JSON数组反序列化。路径''',行1,位置1。
您的json字符串被包装在方括号内([]
),因此它被解释为数组,而不是单个RetrieveMultipleResponse
对象。因此,您需要将其反序列化为RetrieveMultipleResponse
的类型集合,例如:
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
如果要支持泛型(在扩展方法中),这是一个模式...
public static List<T> Deserialize<T>(this string SerializedJSONString)
{
var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
return stuff;
}
它是这样使用的:
var rc = new MyHttpClient(URL);
//This response is the JSON Array (see posts above)
var response = rc.SendRequest();
var data = response.Deserialize<MyClassType>();
MyClassType如下所示(必须匹配JSON数组的名称值对)
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class MyClassType
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "Manager")]
public string Manager { get; set; }
[JsonProperty(PropertyName = "LastUpdate")]
public DateTime LastUpdate { get; set; }
}
使用NUGET下载NewtonSoft.json在需要的地方添加引用...
using Newtonsoft.Json;