【问题标题】:Json formatting from dictionary C#来自字典 C# 的 Json 格式
【发布时间】:2018-07-17 01:23:58
【问题描述】:

您好,我有一本正在使用的字典。

Dictionary<string, string> myProperties

我正在尝试将其格式化为 JSON,但遇到了困难。我需要它是这样的:

    {
     "properties": [
      {
        "property": "firstname",
        "value": "John"
      },
      {
        "property": "lastname",
        "value": "Doe"
      },
      {
        "property": "country",
        "value": "united states"
      }
    ]
  }

目前我正在使用 Json.NET 来序列化字典,但这给了我这个:

{
  "country": "united states",
  "firstname": "John",
  "lastname": "Doe"
}

谁能帮我把它格式化成我需要的格式。任何帮助将不胜感激。

【问题讨论】:

  • 如果您使用 Visual Studio 的 编辑 -> 选择性粘贴 -> 将 JSON 粘贴为类 将所需的 JSON 粘贴到代码中,它将创建该 JSON 所需的类(您需要List&lt;Of Them&gt;)。这样的课程也会让你过去的问题变得更容易。

标签: c# json http dictionary json.net


【解决方案1】:

您可以通过将结果从.Select() 发送到封装在匿名类中的 json 序列化程序,但如果您打算构建更大的东西,我建议您使用真正的类。

JsonConvert.SerializeObject(
  new {properties = myProperties.Select(kv => new { property = kv.Key, value = kv.Value})}
  ,Formatting.Indented);

这会给你

{
  "properties": [
    {
      "property": "firstname",
      "value": "John"
    },
    {
      "property": "lastname",
      "value": "Doe"
    },
    {
      "property": "country",
      "value": "united states"
    }
  ]
} 

【讨论】:

  • 非常感谢!直截了当地说,ToList() 方法是什么格式将其格式化为每个属性的“键”“值”?
  • 是的,我根据@nvoigt 的反馈更新了解决方案,以使其完全按照您的要求进行
  • ToList() 方法将返回包含字典的List&lt;KeyValue&lt;string, string&gt;&gt;。这将被序列化。
【解决方案2】:

基于 N0b1ts 答案:

JsonConvert.SerializeObject(new { properties = myProperties.Select(kvp => new { property = kvp.Key, value = kvp.Value }).ToList() }, Formatting.Indented);

【讨论】:

  • 无需在IEnumerable&lt;TResult&gt; 上使用.ToList()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 2018-12-06
  • 2011-11-06
  • 2012-03-19
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多