我正在使用Dapper返回一个IEnumerable<dynamic>
对象,其签名为:
date: 01/01/2011
VarName = "VariableX"
VariableValue = "Value 1"
date: 01/01/2011
VarName = "VariableY"
VariableValue = "Value 2"
我希望将此转换为JSON响应:
{ date: 01/01/2011
VariableX: Value 1
VariableY: Value 2
}
..等等,并欣赏从哪里开始的任何要点!
由于
编辑:
如果我将对象展平,我会看到:
[
{"date":"\/Date(1331683206000)\/","VariableName":"Variable1","VariableValue":"ValueX"},
{"date":"\/Date(1331683206000)\/","VariableName":"Variable2","VariableValue":"ValueY"},
{"date":"\/Date(1331683206000)\/","VariableName":"Variable3","VariableValue":"ValueZ"}
]
我基本上寻求指导的是如何将其翻转为:
[
{"date":"\/Date(1331683206000)\/","Variable1","ValueX"},
{"date":"\/Date(1331683206000)\/","Variable2","ValueY"},
{"date":"\/Date(1331683206000)\/","Variable3","ValueZ"},
]
编辑#2:修正了所需的输出:
[
{
"date": "/Date(1331683206000)/",
"Variable1": "ValueX"
},
{
"date": "/Date(1331683206000)/",
"Variable2": "ValueY"
},
{
"date": "/Date(1331683206000)/",
"Variable3": "ValueZ"
}
]
编辑#3:
{
"date": "/Date(1331683206000)/",
"Variable1": "ValueX",
"Variable2": "ValueY",
"Variable3": "ValueZ"
},
{
"date": "/Date(1431683206000)/",
"Variable1": "ValueX",
"Variable2": "ValueY",
"Variable3": "ValueZ"
},
{
"date": "/Date(151683206000)/",
"Variable1": "ValueX",
"Variable2": "ValueY",
"Variable3": "ValueZ"
}
答案 0 :(得分:3)
我基本上寻求指导的是如何将其翻转为:
[
{"date":"\/Date(1331683206000)\/","Variable1","ValueX"},
{"date":"\/Date(1331683206000)\/","Variable2","ValueY"},
{"date":"\/Date(1331683206000)\/","Variable3","ValueZ"}
]
我担心这是不可能的,因为您想要的输出是无效 JSON。
如果你的意思是:
[
["\/Date(1331683206000)\/","Variable1","ValueX"],
["\/Date(1331683206000)\/","Variable2","ValueY"],
["\/Date(1331683206000)\/","Variable3","ValueZ"]
]
那么这是完全不同的事情。
更新:
在显示您实际需要的JSON之后,您可以预测结果以实现它:
IEnumerable<dynamic> result = ....
var viewModel = result.Select(x =>
{
var result = new Dictionary<string, object>();
result["date"] = x.date;
result[x.VariableName] = x.VariableValue;
return result;
}).ToList();
return Json(viewModel, JsonRequestBehavior.AllowGet);