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