Darien Fawkes
Darien Fawkes

Reputation: 119

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?

Upvotes: 0

Views: 4228

Answers (2)

Vijay Sirigiri
Vijay Sirigiri

Reputation: 4711

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

Upvotes: 1

JK.
JK.

Reputation: 21810

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()
{
}

Upvotes: 3

Related Questions