0

我正在尝试从活动目录格式化我的数据,以便我可以将其传递JavaScriptSerialzer并以 JSON 格式输入。它还必须采用以下格式: [{"id":"1","name":"Foo"}, {"id":"2","name":"Bar"}]

foreach (SearchResult sResultSet in search.FindAll())
{
    if (sResultSet.Properties["displayName"].Count > 0)
    {
            nameList.Add(string.Format("({0}-{1})",sResultSet.Properties["displayName"][0], sResultSet.Properties["mail"][0])); 
    }
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string output = serializer.Serialize(nameList);

return nameList.ToArray();
4

1 回答 1

0

您的代码看起来不错,但需要进行一些调整。

首先,创建一个DTO类型类以根据需要对其进行序列化并传输,例如:

public class NameDTO
{
   public string Id { get; set; }
   public string Name { get; set; }
}

之后,创建此对象的列表并序列化

// create a list of DTO
var nameList = new List<NameDTO>();

// loop your data
foreach (SearchResult sResultSet in search.FindAll())
{
    // some custom condition
    if (sResultSet.Properties["displayName"].Count > 0)
    {
        // create a DTO object and fill it (i'm not sure about your code)
        var dto = new NameDTO() {
           Id = sResultSet.Properties["mail"][0],
           Name = sResultSet.Properties["displayName"][0]
        }

        // add on the list
        nameList.Add(dto); 
    }
}

// create the serializer object
JavaScriptSerializer serializer = new JavaScriptSerializer();

// serialize the list of DTO and get the result json
string output = serializer.Serialize(nameList);
于 2013-09-20T20:56:17.313 回答