Ramveer Singh
Ramveer Singh

Reputation: 39

Deserialize JSON string into a C# complex class object containing a reference of itself inside

have class whose structure is like

class QuestionNode
{
    public String Value { get; set; }
    public int? QId { get; set; }
    public String QuesDiscription { get; set; }
    public String QuesType { get; set; }
    public String Editable { get; set; }
    public int? PrevQues { get; set; }
    public String UserResponse { get; set; }
    public int UserSelected { get; set; }
    public int Progress { get; set; }

    public List<QuestionNode> OptionSet { get; set; }
    public QuestionNode(int? QId,int? PreQues, String Value){}
    public QuestionNode(int? PreQues, String Value){}
    public QuestionNode (String Value,int? QId,string QuesDiscription,string QuesType ,string Editable ,int?  PrevQues,int? NextQues,int Progress ){}
    public QuestionNode(String Value, int? QId, string QuesDiscription, string QuesType, string Editable, int? PrevQues, int UseResponse, int UserSelected, int Progress, List<QuestionNode> OptionSet){}

}

I am able to convert this structure into json using NewtonSoft.Json. but while Deserializeing it using

Newtonsoft.Json.JsonConvert.DeserializeObject<QuestionNode>(json);

I am getting this exception:

Unable to find a constructor to use for type TestingJson.QuestionNode.
A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'Ques', line 2, position 10.

Upvotes: 0

Views: 220

Answers (1)

JDurstberger
JDurstberger

Reputation: 4255

As the exception states you have to add a default constructor:

class QuestionNode
{
    QuesionNode(){} //Empty default constructor for deserializer

    public String Value { get; set; }
    public int? QId { get; set; }
    //More properties....
}

Upvotes: 1

Related Questions