I'm creating objects based on search results I get. I'm then trying to serialize the objects to return a JSON formatted string. I'm trying to accomplish the below scenario. I don't want to hard-code any JSON, I want the JSON to be output just from the object serialization. I'm not sure how to accomplish what I'm looking for. Note I have some user values hard-coded in my example code for simplicity's sake.
My code:
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 = "[email protected]";
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; }
}
}
My current output:
{"userName":"jsmith","email":"[email protected]","createdDate":"3/20/2016"}, {"userName":"jsmith","email":"[email protected]","createdDate":"3/20/2016"}, {"userName":"jsmith","email":"[email protected]","createdDate":"3/20/2016"}
My desired output:
{
"users": [{
"userName": "jsmith",
"email": "[email protected]",
"createdDate": "3/20/2016"
}, {
"userName": "jsmith",
"email": "[email protected]",
"createdDate": "3/20/2016"
}, {
"userName": "jsmith",
"email": "[email protected]",
"createdDate": "3/20/2016"
}]
}