Search code examples
c#jsonasp.net-web-apiidictionary

c# JSON object dynamic variables


I have a requirement to generate the following JSON using c# objects:

Right now Im using HttpResponseMessage (Web API) So I dont need any JSON.NET to do any extra conversion from my object.

returnVal = Request.CreateResponse(HttpStatusCode.OK, new Model.Custom.JsonResponse
                {
                    data = root,
                    success = true
                });

This is the JSON that I need to generate:

'data': [{
     'some var 1': 'value A',
     'some var 2': 'value B',
     'some var 3': 'value C'
 }, {
     'some var 1': 'value A',
     'some var 2': 'value B',
     'some var 3': 'value C'
 }, {
     'some var 1': 'value A',
     'some var 2': 'value B',
     'some var 3': 'value C'
 }]

Where 'some var' is dynamic.

Right now I was trying to use List<Dictionary<string,object>>(); but the problem is that with this approach I can only generate this:

 'data': [{
     'some var 1': 'value A'
 }, {
     'some var 1': 'value A'
 }, {
     'some var 1': 'value A'
 }]

My actual classes look like this:

public class RootObject {
    public bool success {
        get;
        set;
    }
    public List < Dictionary < string, object >> jsonData {
        get;
        set;
    }
}

var root = new RootObject();

root.jsonData = new List < Dictionary < string, object >> ();

// create new record
var newRecord = new Dictionary < string,object > ();
newRecord.Add("1", "H"); // 1 = some var 1, H = value A 
// add record to collection
root.jsonData.Add(newRecord);

// create new record
newRecord = new Dictionary < string, object > ();
newRecord.Add("5", "L");
// add record to collection
root.jsonData.Add(newRecord);

So this will output:

 'data': [{
     '1': 'H'
 }, {
     '5': 'L'
 }]

Any clue? Thanks


Solution

  • public class MyClass
    {
        public List<JObject> data = new List<JObject>();
    }
    

    var m = new MyClass();
    m.data.Add(new JObject());
    m.data.Add(new JObject());
    
    m.data[0]["some var 1"] = "value A";
    m.data[0]["some var 2"] = "value B";
    m.data[0]["some var 3"] = "value C";
    
    m.data[1]["some var 1"] = "value A";
    m.data[1]["some var 2"] = "value B";
    m.data[1]["some var 3"] = "value C";
    
    var json = JsonConvert.SerializeObject(m);
    

    OUTPUT

    {
      "data": [
        {
          "some var 1": "value A",
          "some var 2": "value B",
          "some var 3": "value C"
        },
        {
          "some var 1": "value A",
          "some var 2": "value B",
          "some var 3": "value C"
        }
      ]
    }