如何在C#中创建JSON-Array,以便我们可以插入一个变量(电子邮件数组),例如“test @ gmail; test1 @gmail ...”?
[
{
"To":[
{
"EntryType":2,
"username":"jack",
"email":"test@gmail.com"
}
],
"Cc":[
{
"EntryType":2,
"username":"mikle",
"email":"test1@gmail.com"
},
{
"EntryType":2,
"username":"jone",
"email":"test2@gmail.com"
}
],
"Bcc":[
{
"EntryType":2,
"username":"luis",
"email":"test3@gmail.com"
}
]
}
]
答案 0 :(得分:1)
答案 1 :(得分:1)
我使用json2csharp.com从您的JSON生成C#类。结果如下:
public class Recepient
{
public int EntryType { get; set; }
public string username { get; set; }
public string email { get; set; }
}
public class Mail
{
public List<Recepient> To { get; set; }
public List<Recepient> Cc { get; set; }
public List<Recepient> Bcc { get; set; }
}
实际上它创建了另外四个类RootObject
,To
,Cc
和Bcc
,但我将其重命名为Mail
和Recipient
。< / p>
要使用Newtonsoft.Json从这些类创建JSON,您可以这样做:
using Newtonsoft.Json;
public string Demo()
{
var mails = new List<Mail>();
var mail = new Mail();
mail.To = new List<Recepient>{
new Recepient
{
EntryType = 2,
username = "jack",
email = "test@gmail.com"
}
};
mail.Cc = new List<Recepient>();
mail.Bcc = new List<Recepient>();
mails.Add(mail);
return JsonConvert.SerializeObject(mails);
}