我需要使用 c# 对象生成以下 JSON:
现在我使用 HttpResponseMessage (Web API) 所以我不需要任何 JSON.NET 来从我的对象进行任何额外的转换。
returnVal = Request.CreateResponse(HttpStatusCode.OK, new Model.Custom.JsonResponse
{
data = root,
success = true
});
这是我需要生成的 JSON:
'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'
}]
哪里'some var'
是动态的。
现在我正在尝试使用List<Dictionary<string,object>>();
,但问题是使用这种方法我只能生成:
'data': [{
'some var 1': 'value A'
}, {
'some var 1': 'value A'
}, {
'some var 1': 'value A'
}]
我的实际课程如下所示:
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);
所以这将输出:
'data': [{
'1': 'H'
}, {
'5': 'L'
}]
有什么线索吗?谢谢