简体   繁体   中英

forming json from dictionary keys in c#

I have this code in c# that gives me a dictionary of my data by date, it works perfect except when the key is serialized into json. the json ends up to be just the toString() property of the class instead of the property name and value I expect. Items in the collection for each of the keys serialize fine. This is my code:

  list = m
  .GroupBy(x => new StatCallDateModel { DateText = x.DateText })
  .ToDictionary(x => x.Key, x => x.ToList()
  .ConvertAll(c => (object)new { Agent = c.Agent, Talk = c.Talk }));
   return list;

One thing I did notice was that when I add the date object to the collection under the key the json parses fine. It is just the fact that it is a key in a dictionary that makes it parse like this. I am using this code to form the json for d3 charts; so the format is important.

Is there a way around this or can I get json similar to this without a dictionary?

I found this post on stack overflow

It pointed me in the right direction, the short answer is a dictionary with a string for a key got me most of the way there...I just wanted to use the key as a property in the script in d3.

 List<object> ops = m.GroupBy(x => x.Agent).ToList()
 .ConvertAll(c => (object)new { Agent = c.First().Agent});
  list = m
 .GroupBy(x => string.Format(@"""DateText"": {0}", x.DateText ))
 .ToDictionary(x => x.Key, x => x.ToList()
 .ConvertAll(c => (object)new { Datetext = c.DateText,  Agent = c.Agent, 
  Talk = c.Talk  })));
  list.Add("keys", ops);

So this code is keyed by a date string and has the keys for the Agents in the final key of the dictionary. Without changing the sql at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM