0

我正在使用 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"
    }
4

1 回答 1

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);
于 2013-06-03T10:58:03.090 回答