序列化来自nhibernate的json数据

时间:2014-10-23 20:22:04

标签: ajax json nhibernate fluent-nhibernate

我知道这有几个主题,但没有一个解决了我的问题。我正在尝试通过Fluent nHibernate从ms sql db中提取数据,并将其序列化为json数据到前端。这是我的nHibernate代码:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetClans()
{
    string output = string.Empty;

    IList<Clan> clans = Counter.Strike.Database.Clan.GetAllClans();

    Clan[] clanJson = new Clan[clans.Count];

    for (int i = 0; i < clans.Count; i++ )
    {
        clanJson[i] = new Clan();
        clanJson[i].Clan_Id = clans[i].Clan_Id;
        clanJson[i].Clan_Name = clans[i].Clan_Name;
    }

    output = JsonConvert.SerializeObject(clanJson);
    return output;
}

我使用的是与此处相同的概念:http://www.codeproject.com/Articles/45275/Create-a-JSON-WebService-in-ASP-NET-with-a-jQu Clan表有一个对Users表的循环引用,这就是我创建一个要序列化的临时对象的原因。我的JSON数据如下所示:

[
    {
        "Clan_Id": 1,
        "Clan_Name": "Dog LB",
        "Owner": null,
        "DateRegistered": "0001-01-01T00:00:00"
    },
    {
        "Clan_Id": 2,
        "Clan_Name": "Frazzes",
        "Owner": null,
        "DateRegistered": "0001-01-01T00:00:00"
    },
    {
        "Clan_Id": 3,
        "Clan_Name": "Goobers",
        "Owner": null,
        "DateRegistered": "0001-01-01T00:00:00"
    },
    {
        "Clan_Id": 4,
        "Clan_Name": "DooGooers",
        "Owner": null,
        "DateRegistered": "0001-01-01T00:00:00"
    }
]

最后这是我的AJAX电话:

<script type="text/javascript" src='<%=Page.ResolveUrl("~/Scripts/jquery-2.1.1.min.js") %>'>     </script>

<script>
window.onload = function () {
    $.ajax({
        type: "POST",
        url: "http://localhost:8379/Services/CounterStrike.asmx/GetClans",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $.each(msg.d, function (index, elem) {
                alert(index + ":" + elem);
            });
        },
        error: function (xhr, ajaxOptions, thrownError)
        { alert(xhr.status); alert(thrownError); }
    });
}
</script>

我的HTML:

<p>
   <b>Choose a Clan:</b>
   <select id="clans">
      <option value="-1">-- Select a Clan --</option>
   </select>
</p>
<div id="users"></div>

在页面加载时,我正在对数据库进行ajax调用,以轮询序列化为json的部落列表并填充下拉列表。不幸的是,我没有得到每个战队的弹出窗口。相反,我检查了javascript控制台并看到:

  

未捕获的TypeError:无法使用'in'运算符来搜索'353'   [{ “Clan_Id”:1, “Clan_Name”:“狗   LB”, “所有者”:NULL, “DateRegistered”: “0001-01-01T00:00:00”},{ “Clan_Id”:2 “Clan_Name”: “Frazzes”, “所有者”:NULL, “DateRegistered” : “0001-01-01T00:00:00”},{ “Clan_Id”:3 “Clan_Name”: “Goobers”, “所有者”:NULL, “DateRegistered”: “0001-01-01T00:00:00” },{ “Clan_Id”:4 “Clan_Name”: “DooGooers”, “所有者”:NULL, “DateRegistered”: “0001-01-01T00:00:00”}]

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

啊哈哈!成功。经过两天的挖掘,我发现我需要的只是在我的响应数据中添加一个eval:

success: function (msg) {
        $.each(eval(msg.d), function (index, elem) {
            alert(index + ":" + elem);
        });
    },

一切正常!