【问题标题】:forming json from dictionary keys in c#从C#中的字典键形成json
【发布时间】:2017-05-03 14:01:40
【问题描述】:

我在 c# 中有这段代码,它按日期为我提供了一个数据字典,它可以完美运行,除非将密钥序列化为 json。 json 最终只是类的 toString() 属性,而不是我期望的属性名称和值。每个键的集合中的项目都可以很好地序列化。这是我的代码:

  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;

我注意到的一件事是,当我将日期对象添加到键下的集合中时,json 解析得很好。只是它是字典中的一个键,使它像这样解析。我正在使用此代码为 d3 图表形成 json;所以格式很重要。

有没有办法解决这个问题,或者我可以在没有字典的情况下获得与此类似的 json 吗?

【问题讨论】:

  • return base.ToString().Replace(base.ToString(), string.Format(@"{{ ""DateText"":""{0}"", }}", this.DateText)); 你有没有一步一步地想清楚这段代码在做什么?无论如何,如果你使用的是 json.NET,this answer seems to address the problem you're having.
  • 你确定你想要的 json 是一个有效的 json 吗?你应该为你的代理数组命名,比如"Agents" : [{ "Agent : "wade"
  • 检查您的 json 以进行验证 jsonlint.com

标签: c# json linq dictionary


【解决方案1】:

I found this post on stack overflow

它为我指明了正确的方向,简短的回答是一个带有字符串的字典,其中一个键让我大部分时间都在那里......我只是想在 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);

因此,此代码由日期字符串作为键,并且在字典的最终键中具有代理的键。根本不改变sql。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2022-10-24
    • 2021-09-16
    相关资源
    最近更新 更多