Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex C# object

I am used to making JavaScript objects like below but what would be the fastest way of doing the same with C#? It is just static data that will be serialized for a post that will not change. In the past with C# I would create classes and lists for everything but in this scenario I just need to send some practice data. Any help would be appreciated

            var data = {
                "dealer": {
                    "keyId": "vfase32sd",  
                     "name": "mark"
                },
                "seller": [
                    {
                        "email": "[email protected]",
                        "active":false
                    }
                ],
                "state": [
                    "TN",
                    "TX"
                ]};
like image 711
Sealer_05 Avatar asked Jun 09 '26 17:06

Sealer_05


1 Answers

See Object and Collection Initializers

Object initializer with Anonymous types

Although object initializers can be used in any context, they are especially useful in LINQ query expressions. Query expressions make frequent use of anonymous types, which can only be initialized by using an object initializer, as shown in the following declaration.

var pet = new { Age = 10, Name = "Fluffy" };

For example:

var data = new
{
    dealer = new
    {
        keyId = "vfase32sd",
        name = "mark"
    },
    seller = new[] {
        new {
            email= "[email protected]",
            active= false
        }
    },
    state = new[]{
        "TN",
        "TX"
    }
};

The rule for converting that js object to c# object is simple:

  • "x": will be x=
  • {} will be new {}
  • [] will be new []{}
  • Values remain untouched
like image 132
Reza Aghaei Avatar answered Jun 12 '26 08:06

Reza Aghaei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!