0

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?

2 Answers 2

3

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()
{
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'am impressed) It,s helped. But I think that I already have the necessary method with one argument: ProductType(string Name)( id = Guid.NewGuid();this.name = Name;) and it won't work.
The error message says "have a default constructor" - that means no arguments.
The error also says "or only one constructor with arguments". So if you don't need both of those constructors then delete one of ProductType(string Name) or ProductType(Guid Id, string Name)
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.