【问题标题】:Webservice - cannot be serialized because it does not have a parameterless constructorWebservice - 无法序列化,因为它没有无参数构造函数
【发布时间】:2014-05-23 18:43:10
【问题描述】:

我从 Web 服务调用以下方法 - 我不断收到一条错误消息“无法序列化,因为它没有无参数构造函数。”

  [WebMethod]
    public ArrayList GetPayers()
    {
        string PROVIDER_JSON = "";

        ArrayList list = new ArrayList();
        using (var webClient = new System.Net.WebClient())
        {
            PROVIDER_JSON = webClient.DownloadString("https://www.eligibleapi.com/resources/information-sources.json");

            List<EligibleProviderType2> UserList = JsonConvert.DeserializeObject<List<EligibleProviderType2>>(PROVIDER_JSON);

            for (int i = 0; i < UserList.Count; i++)
            {
                foreach (string inventoryItem in UserList[i].PayerName)
                {
                    list.Add(new
                    {
                        PayerID = UserList[i].PayerID,
                        PayerName = inventoryItem
                    });
                }
            }

            return list;
        }
    }

哪个调用这个类 - 我认为它有一个无参数的构造函数?

[JsonObject(MemberSerialization.OptIn)]
public class EligibleProviderType2
{
    EligibleProviderType2(){}

    [JsonProperty(PropertyName = "payer_id")]
    public string PayerID { get; set; }

    [JsonProperty(PropertyName = "names")]
    public IList<string> PayerName { get; set; }

} // EligibleProvider

【问题讨论】:

  • ASMX 是一项遗留技术,不应用于新开发。 WCF 或 ASP.NET Web API 应用于 Web 服务客户端和服务器的所有新开发。一个提示:微软已经在 MSDN 上停用了ASMX Forum

标签: c# asp.net web-services asmx


【解决方案1】:

公开你的构造函数。序列化代码看不到。

【讨论】:

    【解决方案2】:

    您的EligibleProviderType2 的构造函数似乎是private。 Private 是类字段和方法的默认值。删除它(因为编译器会为你创建一个)或更改如下:

    [JsonObject(MemberSerialization.OptIn)]
    public class EligibleProviderType2
    {
        public EligibleProviderType2(){}
    
        [JsonProperty(PropertyName = "payer_id")]
        public string PayerID { get; set; }
    
        [JsonProperty(PropertyName = "names")]
        public IList<string> PayerName { get; set; }
    } // EligibleProvider
    

    【讨论】:

    • 我复制了第二个块并粘贴了它,但仍然得到它 - 让我发疯 - 所以现在我有了:public EligibleProviderType2(){}
    • System.InvalidOperationException:生成 XML 文档时出错。 ---> System.InvalidOperationException: <>f__AnonymousType0`2[System.String,System.String] 无法序列化,因为它没有无参数构造函数。在 System.Xml.Serialization.TypeScope.GetTypeDesc(类型类型,MemberInfo 源,布尔 directReference,布尔 throwOnError)在 System.Xml.Serialization.XmlSerializationWriter.CreateUnknownTypeExcep
    • 我在错误中看到这一行:<>f__AnonymousType0`2[System.String,System.String] - 那是什么?
    • 我在LinqPad 中尝试了您的示例,它能够使用 JSON.NET 正确反序列化。确保您已重建和重新部署(如果不是从 IIS Express 本地测试)。我收到的 JSON 数据包含 547 项。
    猜你喜欢
    • 1970-01-01
    • 2015-12-23
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 2015-09-13
    相关资源
    最近更新 更多