c# – 字典JSON格式

我有一个.NET字典,其中包含来自Entity Framework中的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输出?

最佳答案 我想你已经忘了添加{&在每对ColumName,ColumnValue之间,并将其作为一个数组进行序列化.

相反,您的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);
    }
}

获得的序列化值如下:

{"a":
  [ { "ColumnName":"col1", "ColumnValue":1 },
    { "ColumnName":"col2", "ColumnValue":"two" } ]
}
点赞