Amrit
Amrit

Reputation: 421

Class Object with Dynamic Structure

Hi Am trying to parse a json Object with Help of C# DataContractJsonSerializer And this is what json may look like

{"user_id":"121","Q1":"question 1","Q2":"question 2","Q3":"question 3"}

And Number of question can be 200- 500, So I dont want to make a DataContract with 500 Variables to parse this Json, So I was thinking if there is a way where i can call the constructor or something for this class object with a number parameter like this if there are Q1 - Q30 in jSon

Objectparse new_object = new Objectparse(30);

Which will create variables Q1 to Q30 at runtime? and parse the Json

Upvotes: 0

Views: 125

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

You could use JavaScriptSerializer:

var json = @"{""user_id"":""121"",""Q1"":""question 1"",""Q2"":""question 2"",""Q3"":""question 3""}";
var serializer = new JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(json);
Console.WriteLine(result["Q1"]);
Console.WriteLine(result["Q2"]);
...

and if you are using an older version of .NET than 4.0 and cannot use the dynamic feature you could do this:

var json = @"{""user_id"":""121"",""Q1"":""question 1"",""Q2"":""question 2"",""Q3"":""question 3""}";
var serializer = new JavaScriptSerializer();
var result = (IDictionary<string, object>)serializer.DeserializeObject(json);
Console.WriteLine(result["Q1"]);
Console.WriteLine(result["Q2"]);
...

But let me point out that this is an extremely poor JSON design. The person that designed this class was probably not aware of javascript arrays:

{
    "user_id": "121",
    "questions": [
        {
            "key": "Q1",
            "value": "question 1"
        },
        {
            "key": "Q2",
            "value": "question 2"
        },
        {
            "key": "Q3",
            "value": "question 3"
        }
    ]
}

Which could now be serialized into a strongly typed object containing a collections of questions.

Upvotes: 2

Related Questions