4

我有一个 .NET 字典,其中包含来自实体框架中的 SQL 函数的项目。这是我将项目添加到字典的代码:

    public FooViewModel GetFoo()
    {

        var fooresults = new FooResultsViewModel();

        using (var db = new DBEntities())
        {
            var results = db.FunctionResults().ToList();
            foreach (var d in results)
            {
                foo.a.Add(d.ColumnName, d.ColumnValue);
            }


        }
        return fooresults;

这是我的模型:

public class FooViewModel : GraphViewModel
{
    public FooResultsViewModel() { }
    public Dictionary<string, decimal> a = new Dictionary<string, decimal>();
}

最后这是我的控制器:

    public virtual JsonResult GetData()
    {
        var fooresults = new FactSurveryResultsQueries().GetAverages();
        return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = fooresults };
    }

这是返回的 JSON:

{"a":
{"FooResult1":3.579831,
"FooResult2":3.359243,
"FooResult3":3.720588,
"FooResult4":3.636554,
"FooResult5":3.285714,
"FooResult6":3.758403,
"FooResult7":3.262605}}

但是我正在寻找返回的东西,例如:

{"a":
{ColumnName:"FooResult1", 
ColumnValue:3.579831,
ColumnName:"FooResult2",
ColumnValue:3.359243,
ColumnName:"FooResult3",
ColumnValue:3.720588,
ColumnName:"FooResult4",
ColumnValue:3.636554,
ColumnName:"FooResult5",
ColumnValue:3.285714,
ColumnName:"FooResult6",
ColumnValue:3.758403,
ColumnName:"FooResult7",
ColumnValue:3.262605}}

有没有办法为第二个结果格式化 JSON 输出?

4

1 回答 1

3

我想您忘记在每对 , 之间添加{&并将其序列化为数组。}ColumNameColumnValue

相反,您的 JSON 无效或不是 JSON,因为您多次重复相同的属性名称。

如果我是对的,这是一个以您想要的方式塑造字典的测试用例:

[TestClass]
public class CustomDictionaryJsonSerialization
{
    [TestMethod]
    public void SerializeDictionary()
    {
        Dictionary<string, object> dict
            = new Dictionary<string, object> {{"col1", 1}, {"col2", "two"}};

        var nameValues = dict.Keys.Select(k =>
            new {ColumnName = k, ColumnValue = dict[k]});

        var toSerialize = new {a = nameValues.ToList()};

        string serialized = JsonConvert.SerializeObject(toSerialize);

        Assert.IsNotNull(serialized);
    }
}

得到的serialized值是这样的:

{"a":
  [ { "ColumnName":"col1", "ColumnValue":1 },
    { "ColumnName":"col2", "ColumnValue":"two" } ]
}
于 2013-04-04T14:44:47.727 回答