首页 > 解决方案 > 使用 Newtonsoft.Json c# 序列化数组

问题描述

app.config我的项目文件中有一些参数。我想为客户做这些参数尽可能简单

<add key="name" value="Incognito"/>
<add key="emails[0].type" value="Personal"/>
<add key="emails[0].email" value="abc@abc.com"/>

我需要从这些参数中做 JSON。现在我使用Dictionary

var parameters = new Dictionary<string, string>();
for (int i = 0; i < settings.Count; i++)
{
    parameters.Add(settings.GetKey(i), settings[i]);
}
var jsonData = JsonConvert.SerializeObject(parameters);

在这种情况下,我的结果是:

{ "name": "Incognito", "emails[0].type": "Personal", "emails[0].email": "abc@abc.com" }

但我想看看通常的 JSON 数组:

{ "name": "Incognito", "emails": [{"type": "Personal", "email": "abc@abc.com"}, {...}] }

我怎样才能做到这一点?如何正确序列化它?或者,也许您知道一种以app.config人类可读格式写入数据的方法?

标签: c#arraysjsonjson.net

解决方案


To get a JSON array you'll need to use something more like an array, say perhaps an Array or List of a type which has both type and email properties.

public class Parameters{
    public string Name { get; set; }
    public List<Email> Emails { get; set; }
}

public class Email{
    public string Type { get; set; }
    public string Email { get; set; }
}

Serialising an instance of Parameters will get you the JSON structure you desire.


推荐阅读