使用 RestSharp 将 JSON 数组反序列化为 C# 结构
Deserialize JSON array into C# Structure with RestSharp
我使用 RestSharp 和 IRestResponse<T> response = client.Execute<T>(request)
动态地将不同的 JSON 结构放入各种 C# 结构中。但是,一个特定的 JSON 结果给我带来了麻烦,它以方括号开头和结尾...
我的 JSON 以“[”和“]”字符开头和结尾:
[
{
"first": "Adam",
"last": "Buzzo"
},
{
"first": "Jeffrey",
"last": "Mosier"
}
]
我创建了这个 class 结构:
public class Person
{
public string first { get; set; }
public string last { get; set; }
}
public class Persons
{
public List<Person> person { get; set; }
}
我在方法中使用 RestSharp 动态反序列化到我的 Persons 类型 T...
IRestResponse<T> response = client.Execute<T>(request);
return response;
问题是,当 T 是 Persons 时,我在 client.Execute 行收到此错误:
Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
我也尝试过 Json.Net 并得到了这个错误:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Persons' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.
鉴于初始的“[”字符,我尝试反序列化为 Persons 的 List。这停止了错误消息,我有正确数量的 "Person" 记录,但它们都是空的。 (我确认名称的大小写是相同的。)当目标服务器的数组总是只有一个元素时,我也不想使用 List 集合,因此绑定到 "Persons" 比 "List".
将此 JSON 反序列化为 Persons 并且仍在我的动态 IRestResponse<T> response = client.Execute<T>(request)
方法范围内的正确方法是什么?
如评论中所述,您的 json 包含一组人。因此,要反序列化的目标结构应该与之匹配。
要么使用:
var response = client.Execute<List<Person>>(request);
或者如果您更喜欢 Persons
class,请将其更改为
public class Persons : List<Person>
{
}
我使用 RestSharp 和 IRestResponse<T> response = client.Execute<T>(request)
动态地将不同的 JSON 结构放入各种 C# 结构中。但是,一个特定的 JSON 结果给我带来了麻烦,它以方括号开头和结尾...
我的 JSON 以“[”和“]”字符开头和结尾:
[
{
"first": "Adam",
"last": "Buzzo"
},
{
"first": "Jeffrey",
"last": "Mosier"
}
]
我创建了这个 class 结构:
public class Person
{
public string first { get; set; }
public string last { get; set; }
}
public class Persons
{
public List<Person> person { get; set; }
}
我在方法中使用 RestSharp 动态反序列化到我的 Persons 类型 T...
IRestResponse<T> response = client.Execute<T>(request);
return response;
问题是,当 T 是 Persons 时,我在 client.Execute 行收到此错误:
Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
我也尝试过 Json.Net 并得到了这个错误:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Persons' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.
鉴于初始的“[”字符,我尝试反序列化为 Persons 的 List。这停止了错误消息,我有正确数量的 "Person" 记录,但它们都是空的。 (我确认名称的大小写是相同的。)当目标服务器的数组总是只有一个元素时,我也不想使用 List 集合,因此绑定到 "Persons" 比 "List".
将此 JSON 反序列化为 Persons 并且仍在我的动态 IRestResponse<T> response = client.Execute<T>(request)
方法范围内的正确方法是什么?
如评论中所述,您的 json 包含一组人。因此,要反序列化的目标结构应该与之匹配。 要么使用:
var response = client.Execute<List<Person>>(request);
或者如果您更喜欢 Persons
class,请将其更改为
public class Persons : List<Person>
{
}