使用RestSharp将JSON数组反序列化为C#结构

问题描述:

我正在使用RestSharp和IRestResponse<T> response = client.Execute<T>(request)将不同的JSON结构动态地转换为各种C#结构.但是,一个特殊的JSON结果给我带来麻烦,它的开头和结尾都带有方括号...

I am dynamically taking different JSON structures into various C# structures, using RestSharp and IRestResponse<T> response = client.Execute<T>(request). 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:

[
  {
    "first": "Adam",
    "last": "Buzzo"
  },
  {
    "first": "Jeffrey",
    "last": "Mosier"
  }
]

我创建了这个类结构:

public class Person
{
    public string first { get; set; }
    public string last { get; set; }
}
public class Persons
{
    public List<Person> person { get; set; }
}

我在一种方法中使用RestSharp将其动态反序列化为我的 Person 类型T ...

I use RestSharp within a method to deserialize dynamically into my Persons type T...

IRestResponse<T> response = client.Execute<T>(request);
return response;

问题是当T为 Persons 时,我在客户端上收到此错误.请执行以下行:

The problem is that when T is Persons I get this error on the client.Execute line:

无法将类型为"RestSharp.JsonArray"的对象转换为类型为"System.Collections.Generic.IDictionary`2 [System.String,System.Object]".

Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.

我也尝试使用Json.Net并收到此错误:

I also tried with Json.Net and got this error:

无法将当前JSON数组(例如[1,2,3])反序列化为类型'Persons',因为该类型需要JSON对象(例如{\"name \":\"value \"})才能正确反序列化

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.

考虑到初始的[[]字符,我尝试将其反序列化为人员列表.那停止了错误消息,并且我有正确数量的"Person"记录,但它们都为空. (我确认名称的大小写是相同的.)当目标服务器上的数组中始终只有一个元素,因此绑定"Persons"比"List"更有意义时,我也不想使用List集合.

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".

将这个JSON反序列化为 Persons 并仍在我的动态IRestResponse<T> response = client.Execute<T>(request)方法学范围内的正确方法是什么?

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包含一组人员.因此,要反序列化的目标结构应与此匹配. 可以使用:

As mentioned in the comments, your json holds an array of persons. Therefore the target structure to deserialize to should match that. Either use:

var response = client.Execute<List<Person>>(request);

,或者如果您喜欢Persons类,请将其更改为

or if you prefer the Persons class, change it to

public class Persons : List<Person>
{
}