ASP.. NET MVC格式的JSON响应从一个动态

本文关键字:动态 一个 响应 MVC NET 格式 JSON ASP | 更新日期: 2023-09-27 18:16:39

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

ASP.. NET MVC格式的JSON响应从一个动态

我实际上是在寻找如何翻转它的指导,所以它是:

[
    {"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);