简体   繁体   English

写字典<string, dynamic>到 JSON 文件

[英]Write Dictionary<string, dynamic> to JSON file

If I have a Dictionary<string, dynamic> where the keys use dot notation, is there an easy way to convert to JSON with JSON.NET?如果我有一个Dictionary<string, dynamic>键使用点表示法,是否有一种简单的方法可以使用 JSON.NET 转换为 JSON? For example:例如:

Dictionary<string, dynamic> records = new Dictionary<string, dynamic>
{
    { "Name.First", "John" },
    { "Name.Last", "Doe" },
    { "ContactInfo", new ContactInfo {
        Phone = "555-555-5555",
        Foo = 999,
        Bar = true
    } }
};

Desired JSON would be:所需的 JSON 将是:

{
    "name": {
        "first": "John",
        "last": "Doe"
    },
    "contactInfo": {
        "phone": "555-555-5555",
        "foo": 999,
        "bar": true
    }
}

So, there are many ways to do this.所以,有很多方法可以做到这一点。 However, the main problem is the design choice of the dictionary with dynamic values, without further explanation this seems very suspect.但是,主要问题是dynamic字典的设计选择,没有进一步解释这似乎很可疑。

However, assuming you know best.但是,假设您最了解。 You would have to project your data to another form, or write some sort of converter one way or the other.您必须将数据投影到另一种形式,或者以某种方式编写某种转换器。 I chose an anonymous type , since your data is relatively simple.我选择了匿名类型,因为您的数据相对简单。

var temp = new
{
   name = new
   {
      first = records["Name.First"],
      last = records["Name.Last"],
   },
   ContactInfo = records["ContactInfo"]
};

// this is just one way to get your `ContactInfo` camel case, there are others
var contractResolver = new DefaultContractResolver
{
   NamingStrategy = new CamelCaseNamingStrategy()
};

var json = JsonConvert.SerializeObject(temp, new JsonSerializerSettings()
{
   ContractResolver = contractResolver,
   Formatting = Formatting.Indented
});


Console.WriteLine(json); 

Output输出

{
  "name": {
    "first": "John",
    "last": "Doe"
  },
  "contactInfo": {
    "phone": "555-555-5555",
    "foo": 999,
    "bar": true
  }
}

Note : This answer is not optimal, I would consider revaluating your choices of data structure注意:此答案不是最佳答案,我会考虑重新评估您对数据结构的选择

Use the JsonSerializer.使用 JsonSerializer。 You first need to import it您首先需要导入它

using Newtonsoft.Json;

Then use the following code to get the JSON string然后使用以下代码获取JSON字符串

String json = JsonConvert.SerializeObject(records);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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