为JSON序列化创建和存储对象?

时间:2016-03-20 12:15:28

标签: c# json object serialization

我正在根据我得到的搜索结果创建对象。然后我尝试序列化对象以返回JSON格式的字符串。我正在尝试完成以下方案。我不想硬编码任何JSON,我希望只从对象序列化输出JSON。我不知道如何完成我正在寻找的东西。注意为了简单起见,我的示例代码中有一些硬编码的用户值。

我的代码:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        getSearchResultsString();
    }

    public void getSearchResultsString()
    {
        string[] userList = { "user1", "user2", "user3" };

        var json = "";

        List<string> users = new List<string>();

        foreach (string user in userList)
        {

            string userName = "jsmith";

            string email = "jsmith@example.com";

            string createdDate = "3/20/2016";

            ADUser aduser = new ADUser(userName, email, createdDate);

            users.Add(new JavaScriptSerializer().Serialize(aduser));
        }
        json = String.Join(", ", users);
        Response.Write(json);
    }

    public class ADUser
    {
        public ADUser(string UserName, string Email, string CreatedDate)
        {
            userName = UserName;
            email = Email;
            createdDate = CreatedDate;
        }

        // Properties.
        public string userName { get; set; }
        public string email { get; set; }
        public string createdDate { get; set; }
    }
}

我目前的输出:

{"userName":"jsmith","email":"jsmith@example.com","createdDate":"3/20/2016"}, {"userName":"jsmith","email":"jsmith@example.com","createdDate":"3/20/2016"}, {"userName":"jsmith","email":"jsmith@example.com","createdDate":"3/20/2016"}

我想要的输出:

{
    "users": [{
        "userName": "jsmith",
        "email": "jsmith@example.com",
        "createdDate": "3/20/2016"
    }, {
        "userName": "jsmith",
        "email": "jsmith@example.com",
        "createdDate": "3/20/2016"
    }, {
        "userName": "jsmith",
        "email": "jsmith@example.com",
        "createdDate": "3/20/2016"
    }]
}

1 个答案:

答案 0 :(得分:2)

您可以尝试将getSearchResultsString()修改为打击

public static void getSearchResultsString()
    {
        string[] userList = { "user1", "user2", "user3" };

        var json = "";

        List<ADUser> users = new List<ADUser>();

        foreach (string user in userList)
        {

            string userName = "jsmith";

            string email = "jsmith@example.com";

            string createdDate = "3/20/2016";

            ADUser aduser = new ADUser(userName, email, createdDate);

            users.Add(aduser);
        }
        json = new JavaScriptSerializer().
            Serialize(new { users = users });
        Response.Write(json);
    }