使用数组反序列化json对象失败,并且找不到类型System.String []的Default构造函数

Div*_*Dan 2 json xamarin.ios restsharp c#-4.0

我试图使用restsharp在单触摸项目中反序列化对象时遇到一些麻烦.

我有这个

    RestResponse<List<Product>> response = client.Execute<List<Product>> (request) as RestResponse<List<Product>>;
            if (response.Data != null) {}

    public class Product
{
    public Product () {}
    [PrimaryKey]
    public string Id { get; set; }
    public string Name { get; set; }

    [Ignore]
    public string[] ParentProductIds {
    get;
    set;
}
Run Code Online (Sandbox Code Playgroud)

我收到了错误

找不到类型System.String []的默认构造函数.

我的json看起来像

[ 
    {
    "Id" : "62907011-02f1-440a-92ec-dc35ecf695e0",
    "Name" : "ABC",
    "ParentProductIds" : ["2cedbcad-576a-4044-b9c7-08872de34a96", "3fcd12ce-8117-4ae7-ae4d-f539e4268e4d"]
    }, 
    {
    "Id" : "3fcd12ce-8117-4ae7-ae4d-f539e4268e4d",
    "Name" : "Name 1",
    "ParentProductIds" : null
    }
]
Run Code Online (Sandbox Code Playgroud)

是由于null ParentProductId?

任何人都可以建议我需要做什么才能接受空数组?

小智 9

这个问题的关键是RestSharp使用自己的内部Json Serializer/Deserializer,它不支持数组对象的反序列化(在您的情况下为ParentProductIds).它确实支持List(Generics)对象的反序列化.虽然您的解决方案完全有效,但我相信在某些情况下,更倾向于离开阵列而不是使用泛型.为此,我继续使用RestSharp来处理我的休息请求,但是使用了来自James Newton-King的JsonConvert(来自NuGet的JSon.Net)来从response.Content反序列化.

因此,您可以将Json.Net添加到项目中,添加相应的using语句并使用以下内容反序列化您的响应:

var response = client.Execute(request);
List<Product> product = JsonConvert.DeserializeObject<List<Product>>(response.Content);
Run Code Online (Sandbox Code Playgroud)

额外的好处是JSon.Net是一个更高效的序列化器,因此代码运行速度更快.