【问题标题】:Deserialize a json object with an array fails with Default constructor not found for type System.String[]使用数组反序列化 json 对象失败,找不到类型 System.String[] 的默认构造函数
【发布时间】:2013-06-06 10:45:41
【问题描述】:

我在尝试使用 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;
}

我收到一个错误

找不到 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
    }
]

是因为 null ParentProductId 吗?

谁能告诉我需要做什么才能接受空数组?

【问题讨论】:

    标签: json c#-4.0 xamarin.ios restsharp


    【解决方案1】:

    这个问题的关键是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 是一个更高效的序列化程序,因此代码通常运行得更快。

    【讨论】:

      【解决方案2】:

      使用 List 遇到相同问题的任何其他人都可以正常工作。

      public List<string> ParentProductIds {
          get;
          set;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-23
        • 1970-01-01
        • 2015-07-16
        • 1970-01-01
        相关资源
        最近更新 更多