gpt4 book ai didi

json - 使用数组反序列化 json 对象失败,未找到类型 System.String[] 的默认构造函数

转载 作者:行者123 更新时间:2023-12-05 01:14:57 26 4
gpt4 key购买 nike

我在尝试使用 restsharp 反序列化 monotouch 项目中的对象时遇到了一些麻烦。

我有这个

    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;
}

我得到一个错误

Default constructor not found for type 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
}
]

是不是因为 ParentProductId 为空?

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

最佳答案

这个问题的关键是 RestSharp 使用它自己的内部 Json Serializer/Deserializer,它不支持数组对象的反序列化(在你的例子中是 ParentProductIds)。它确实支持列表(泛型)对象的反序列化。尽管您的解决方案是完全有效的,但我相信在某些情况下,人们更愿意保留数组而不是使用泛型。为此,我继续使用 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);

额外的好处是 JSon.Net 是一个更高效的序列化程序,因此代码通常运行得更快。

关于json - 使用数组反序列化 json 对象失败,未找到类型 System.String[] 的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16960112/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com