Alexander
Alexander

Reputation: 1687

Dictionary JSON Formatting

I have a .NET dictionary containing items from a SQL Function in Entity Framework. Here is my code to add the items to a dictionary:

    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;

Here is my model:

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

Finally here is my controller:

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

And this is the JSON that is returned:

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

However I am looking for something that returns like:

{"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}}

Is there a way to format the JSON output for the second result?

Upvotes: 4

Views: 25221

Answers (1)

JotaBe
JotaBe

Reputation: 39045

I suppose you've forgotten to add { & } between each pair of ColumName, ColumnValue, and serialze it as an array.

On the contrary, your JSON is not valid or is not JSON, because you're repeating the same property name many times.

If I'm right this is a test case that shapes a Dictionary the way you want:

[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);
    }
}

The obtained serialized value is like this:

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

Upvotes: 3

Related Questions