使用asp.net在C#中创建JSON数组

时间:2015-11-18 05:34:31

标签: c# json

如何在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"
            }
        ]
    }
]

2 个答案:

答案 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; }
}

实际上它创建了另外四个类RootObjectToCcBcc,但我将其重命名为MailRecipient。< / 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);
}