[英]Deserialize JSON array into C# Structure with RestSharp
I am dynamically taking different JSON structures into various C# structures, using RestSharp and IRestResponse<T> response = client.Execute<T>(request)
. 我使用RestSharp和
IRestResponse<T> response = client.Execute<T>(request)
动态地将不同的JSON结构转换为各种C#结构。 But, one particular JSON result is giving me trouble, where it starts and ends with brackets... 但是,一个特定的JSON结果给了我麻烦,它以括号开始和结束......
My JSON starts and ends with "[" and "]" characters: 我的JSON以“[”和“]”字符开头和结尾:
[
{
"first": "Adam",
"last": "Buzzo"
},
{
"first": "Jeffrey",
"last": "Mosier"
}
]
I've created this class structure: 我创建了这个类结构:
public class Person
{
public string first { get; set; }
public string last { get; set; }
}
public class Persons
{
public List<Person> person { get; set; }
}
I use RestSharp within a method to deserialize dynamically into my Persons type T... 我在一个方法中使用RestSharp动态地反序列化为我的Persons类型T ...
IRestResponse<T> response = client.Execute<T>(request);
return response;
The problem is that when T is Persons I get this error on the client.Execute line: 问题是,当T是人时,我在客户端上出现此错误。执行行:
Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
无法将类型为'RestSharp.JsonArray'的对象强制转换为'System.Collections.Generic.IDictionary`2 [System.String,System.Object]'。
I also tried with Json.Net and got this error: 我也试过Json.Net并得到了这个错误:
Cannot deserialize the current JSON array (eg [1,2,3]) into type 'Persons' because the type requires a JSON object (eg {\\"name\\":\\"value\\"}) to deserialize correctly.
无法将当前JSON数组(例如[1,2,3])反序列化为“Persons”类型,因为该类型需要JSON对象(例如{\\“name \\”:\\“value \\”})才能正确反序列化。
Given the initial "[" character, I tried deserializing into a List of Persons . 鉴于最初的“[”字符,我尝试反序列化为人员 列表 。 That stopped the error message and I had the right number of "Person" records BUT they were all null.
这停止了错误消息,我有正确数量的“人”记录,但他们都是空的。 (I confirmed casing of names was identical.) I also don't really want to use a List collection when there is always only one element to the array from the target server and so binding to "Persons" makes more sense than "List".
(我确认名称的大小写是相同的。)当目标服务器中只有一个元素到数组时,我也不想使用List集合,因此绑定到“Persons”比“List”更有意义。
What is the correct way to deserialize this JSON into Persons and still within the scope of my dynamic IRestResponse<T> response = client.Execute<T>(request)
methodology? 将此JSON反序列化为人员的正确方法是什么,仍然在我的动态
IRestResponse<T> response = client.Execute<T>(request)
方法的范围内?
As mentioned in the comments, your json holds an array of persons. 正如评论中所提到的,你的json拥有一系列人。 Therefore the target structure to deserialize to should match that.
因此,反序列化的目标结构应与之匹配。 Either use:
使用:
var response = client.Execute<List<Person>>(request);
or if you prefer the Persons
class, change it to 或者如果您更喜欢
Persons
类,请将其更改为
public class Persons : List<Person>
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.