簡體   English   中英

在asp.net中序列化為JSON?

[英]Serializing to JSON in asp.net?

嗨,我第一次在asp.net中使用JSON

我有這樣的WebMethod

               [WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Vo_Get(string Action,int ID)
{
    Product p= new Product();

    DataSet ds= new DataSet();

    p.Action = Action;
    p.ID= ID;

    ds= VoGet_Get(obj);

    **string jsonVesselDetails = JsonConvert.SerializeObject(ds, Formatting.None);
    return jsonVesselDetails;**
}

我在這里得到我的結果

       [
  {
    "Pinky": 1,
    "Ponky": "Breakwater Dockk",

  },
  {
    "Pinky": 2,
    "Ponky": "Watson Island Dock",    
  },

但是當我嘗試使用Ajax進行調用並追加到表中時,如果我嘗試與結果綁定,則給與未擴展令牌U;如果我嘗試與result.data綁定,則給其未預期令牌O。

終於我發現問題在於序列化,

我的Ajax電話是

                  $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Voyage.aspx/Vo_Get",
                data: "{'Action':'Get','ID':'68'}",
                dataType: "json",
                success: function (data) {
                    try {
                        alert("getdata! success" );

                        Get(data);

                    } catch (ex) {
                        alert(ex);
                    }
                },
                error: function (msg) {
                    alert("err: " + error);
                }
            });

我不知道GetVessels期望什么,但是請嘗試:

GetVessels(data.d);

即傳遞實際數據,而不是傳遞整個響應對象。

可能您也在成功函數中使用了相同的變量data 嘗試使用以下內容,

success: function (result) {
   try {
        alert("getdata! success" );

        GetVessels(result);

        //Rebuild the table
        //BuildVesselTaggerInfo();

   } catch (ex) {
        alert(ex);
   }
},

請注意,我已從數據更改為結果。

首先,驗證您的GetVessles方法期望使用哪種JSON或數組結構。

您可以通過直接輸入VoyageVessel_Get方法的JSON響應或手動構造它來實現。

 var data= [
 {
      "TerminalID": 1,
      "TerminalName": "Breakwater Dockk",
      "PortID": 1,
      "PortName": "Swire Pacific Offshore",
      "Column1": "08/03/13",
      "Column2": "16/03/13",
      "ServiceID": 2
  },
  {
      "TerminalID": 2,
      "TerminalName": "Watson Island Dock",
      "PortID": 2,
      "PortName": "Keppel Offshore",
      "Column1": "20/03/13",
      "Column2": "23/03/13",
      "ServiceID": 2
  }];

  GetVessels(data);

查看您的GetVessels適用於該對象。 如果沒有找到所需的結構(只有您可以做到),然后構造它。

其次,您不能直接訪問ASP.NET Web-Service:success的響應。

像這樣訪問它:

success: function (data) {
           var jsonData= data.d;
           GetVessels(jsonData);
 }

更新

如果您的對象包含datetime字段,請嘗試在Serialization指定DateFormathandling,即

JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            };
string serializedObject= Newtonsoft.Json
                     .JsonConvert
                     .SerializeObject(dsVoyages, microsoftDateFormatSettings);

暫無
暫無

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

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