繁体   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