【发布时间】:2016-03-20 12:15:27
【问题描述】:
我正在根据获得的搜索结果创建对象。然后我尝试序列化对象以返回 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"
}]
}
【问题讨论】:
-
不要列出字符串,列出对象!
-
我需要在我的代码中修改/添加什么?
标签: c# json object serialization