0

This is the JSON and I want to map this into the c# object using Newtonsoft.json

{
"PremiumStructure": [
    {
        "Level": true,
        "LevelText": "Level"
    },
    {
        "Stepped": false,
        "SteppedText": "Stepped"
    },
    {
    "DifferentPropetyNameinFuture" : false,
    "DifferentPropetyNameinFutureText" : "stringValue"
    }
    ]

}

3 Answers 3

1

Just use the below approach. Create a RootObj and define a property as List which contains Dictionary :

class MyObj
{
    public List<Dictionary<string, object>> PremiumStructure;
}

class Program
{
    static void Main(string[] args)
    {
        var text = File.ReadAllText("test.json"); // the file contains your json example

        var myObj = JsonConvert.DeserializeObject<MyObj>(text);

        foreach (var item in myObj.PremiumStructure)
        {
            foreach (var key in item.Keys)
            {
                Console.WriteLine($"Key: {key} Value: {item[key]}");
            }
        }

        Console.ReadLine();
    }
}

Output :

Key: Level Value: True
Key: LevelText Value: Level
Key: Stepped Value: False
Key: SteppedText Value: Stepped
Key: DifferentPropetyNameinFuture Value: False
Key: DifferentPropetyNameinFutureText Value: stringValue

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

You can use json2csharp to Convert it to C# classes.

1 Comment

This gives me concrete generated model, but in array I may have more object for that I will have to add more concrete classes to map the model according to json2csharp. So, I want the solution which is generic for it. So that I don't have to change the model instead of increment in objects in array.
0

This gives me concrete generated model, but in array I may have more object for that I will have to add more concrete classes to map the model according to json2csharp. So, I want the solution which is generic for it.

Then you might want to not deserialise the JSON, and just parse it to a JObject instead:

// Remember to add "using Newtonsoft.Json.Linq;"!
JObject root = new JObject.Parse(yourJSONString);

And then use the indexers of root to access the different KVPs. e.g.

root["PremiumStructure"][0]["Level"]

Alternatively, if you want to access the properties with dot notation, deserialise the JSON into a dynamic variable and directly access the properties with that:

dynamic obj = JsonConvert.DeserializeObject(json);
obj.PremiumStructure[0].Level

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.