开发者

Error in DeserializeObject method json?

I have class in my project:

public class ProductType
{
    private string name;
    private Guid id;        

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public Guid Id
    {
        get { return id; }
        set { id = value; }
    }

    public override string ToString()
    {
        return name;
    }

    public ProductType(string Name)
    {
        id = Guid.NewGuid();
        this.name = Name;
    }               

    public ProductType(Guid Id, string Name)
    {
        this.id = Id;
        this.name = Name;
    }       
}

I'm trying to deserialize a json object of this class like the following

strObjJson = "{\"Name\":\"proName\"}";
using this:

ProductType deserializedProductType = JsonConvert.DeserializeObject(strObjJson);

However the following error appears:

开发者_如何学运维
Unable to find a constructor to use for type `ClassLibraryObjects.ProductType`. A class should either have a default constructor or only one constructor with arguments.

How can I repair this?


Well, if the error says:

Unable to find a constructor to use for type ClassLibraryObjects.ProductType. A class should either have a default constructor or only one constructor with arguments.

Then why don't you add a constructor with no arguments?

public ProductType()
{
}


What the exception means is that - You have 2 ctors that each take varied number of args. You also don't have a public ctor which doesn't take parameters.

I noticed that you were expecting Guid to be passed by the caller? which I don't think is necessary. You could modify the code by removing the below ctor (1) and adding a new one (2)

        // (1) remove this from your code
        public ProductType(string Name)
        {
            id = Guid.NewGuid();
            this.name = Name;
        }

        // (2) add this ctor 
        public ProductType(string Name, Guid id = default(Guid))
        {
            this.id = id;
            this.name = Name;
        }

This should do the trick. PS: I tried the code with JavaScriptSerializer from System.Web.Extensions.dll

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜