如何通过C#返回JSON并用JavaScript进行解析

How can I return JSON via C# and parse it in JavaScript?

本文关键字:JavaScript 并用 何通过 返回 JSON      更新时间:2023-09-26

我使用的是一个web服务,它从我的活动目录中获取数据,并向我的javascript返回一组对象。问题是,当我只想返回像这样的对象的值时,我就是封装在Object中的响应,其中包含_type

([{ value: "one", label: "Foo" }, { value: "two", label: "Bar" }]). 

但是我收到了这个

[Object { __type="Service+NameDTO", value: "one", label: "Foo"}, Object { __type="Service+NameDTO", value:     "two", label: "Bar"}]

这是我的c#

public NameDTO[] GetCompletionList(string prefix)
{
    var nameList = new List<NameDTO>();
    DirectorySearcher search = new DirectorySearcher();
    string strPath = search.SearchRoot.Path;
    DirectoryEntry entry = new DirectoryEntry(strPath);
    search.PageSize = 1000;
    search.Filter = "(&(objectClass=user)(objectCategory=person)(displayName=*" + prefix + "*))";
    foreach (SearchResult sResultSet in search.FindAll())
    {
        if (sResultSet.Properties["mail"].Count > 0)
        {
            var dto = new NameDTO()
            {
                label = (string)sResultSet.Properties["displayName"][0],
                value = (string)sResultSet.Properties["mail"][0],
            };
            nameList.Add(dto);
        }
    }
    NameDTO[] myArray = nameList.ToArray();
    return myArray;
}
public class NameDTO
{
    public string label { get; set; }
    public string value { get; set; }
}

和我的javascript

<script type="text/javascript">
    $(document).ready(function () {
        $('#tokenfield').tokenfield({
            autocomplete: {
                source: function (request, response) {
                    $.ajax({
                        url: '<%#ResolveUrl("~/Service1.asmx/GetCompletionList") %>',
                        data: "{ 'prefix': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                           response($.map(data.d, function (item) {
                            return data      
                           }))
                        },
                        success: function(response) {
                            $.each(response, function(key, val) {
                                alert(val.id);
                            });
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                   });
                },
                search: function () {
                var term = this.value;
                if (term.length < 3) {
                    return false;
                }
                },
                focus: function () {
                // prevent value inserted on focus
                return false;
                },
            },
      });
});
</script>

您可能需要一些典型的JSON构建器。

服务器端,您可以制作字典、数组等,并将所有内容放入

JsonMapper.ToJson(jsonDict)

呼叫。

我项目中的这个函数间接调用JsonSerializer(),即Newtonsoft JSON处理程序。对于序列化和反序列化JSON都非常有用。

不过,我可能误解了你的问题;有点含糊。

http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx非常相关,非常有用。

你可能需要这个:

var jsonString = @Model; //or however you get your string.
var json = JSON.parse(jsonString);