私は検索結果に基づいてオブジェクトを作成しています。私はJSON形式の文字列を返すようにオブジェクトをシリアル化しようとしています。私は以下のシナリオを達成しようとしています。 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 = "[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; }
}
}
私の現在の出力:
{"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"}
マイ所望の出力:
{
"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"
}]
}
オブジェクトのリストを作成しないでください! –
コードの変更/追加には何が必要ですか? –