簡體   English   中英

C#Web服務以javascript反序列化JSON對象

[英]C# Web service to javascript Deserializing JSON Object

我有一個Web應用程序。 在內部,我有一個asmx文件“ MyWebServices.asmx”,其中有一個Web方法可以將json對象發送到WebForm2.aspx。 我的問題是如何使用Javascript捕獲此對象並將其存儲並使用javascript顯示它。 我在MyWebServices.asmx上的代碼:

public class apointment
    {
        public string Fname{ get; set; }
        public string Lname{ get; set; }
        public string customerid { get; set; }

    }

[WebMethod]
    public string myapointment()
    {

        apointment myapointment1= new apointment();
       myapointment1.customerid = "123POW";
        myapointment1.Fname = "John";
        myapointment1.Lname = "JohnsLname";
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string sJSON = oSerializer.Serialize(myapointment1);
        return sJSON;
    }

我在.net頁面上的代碼Javascript:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "services/MyWebServices.asmx/myapointment",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {



                // Insert the returned HTML into the <div>.
                var myrant = data.d;

                $('#RSSContent').html(data.d);
            }
        });
    });


</script>

問題是此代碼我正在使用一個字符串:

{"Fname":"John","Lname":"JohnsLname","customerid":"123POW"}

如何將該字符串轉換為對象類型約會? 我問是因為在那之后我可以在html上正確顯示,所以我想創建約會列表。

您是否考慮過將以下代碼用於Web服務。

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public apointment myapointment()
{
    apointment myapointment1 = new apointment();
    myapointment1.customerid = "123POW";
    myapointment1.Fname = "John";
    myapointment1.Lname = "JohnsLname";

    return myapointment1;
}

其次,根據該問題的答案( 從Javascript調用ASMX Web服務 ),您是否已取消注釋此Web服務頂部的行。

//[System.Web.Script.Services.ScriptService]

最終,您是否嘗試過使用Fiddler( http://www.telerik.com/fiddler )調試Web服務以確定Web服務是否返回正確的輸出? Composer標簽用於以下設置:

您應該在頁面的左欄中看到對Web服務的請求。 單擊RawTextView選項卡,然后查看是否顯示您期望的JSON。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM