现在的位置: 首页 > 综合 > 正文

服务器端和客户端数据类型的自动转换:以XML方式序列化数据

2013年09月09日 ⁄ 综合 ⁄ 共 2486字 ⁄ 字号 评论关闭

ASP.NET AJAX异步通讯层在传递数据时默认采用JSON序列化方式,但同时也提供给我们以XML方式进行序列化的选项。 一般来讲,如果某Web Service方法的返回值类型为XmlDocument或XmlElement的话,我们应该让这类返回值以XML方式进行序列化。例如如下的这个Web Service方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDocument GetXmlDocument()
{
    string theString = "<persons>"
        + "<person><name>Tom</name><age>30</age></person>"
        + "<person><name>Jerry</name><age>20</age></person>"
        + "</persons>";
    
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(theString);
 
    return xmlDoc;
}
注意上述代码中的粗体部分,[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]这个属性就将该GetXmlDocument()方法返回值的序列化方
式设置为了XML。在客户端的回调函数中,返回的客户端XML文档对象在Visual Studio调试器中显示出的结构如图3-36所示。
对于非XmlDocument或XmlElement的类型,如果我们愿意,也可以选择将其以XML的方式进行序列化。我们还是以前面定义的Employee类为例,如下
Web Service方法就以XML序列化的方式返回一个Employee对象:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public Employee GetXMLFormatEmployee()
{
    return new Employee(
        12345,
        "Dflying",
        "Dflying@some.com",
        int.MaxValue
    );
}

同样是为该方法应用了[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]属性(代码中粗体部分),在客户端回调函数中,返回

的JavaScript对象在Visual Studio调试器中显示出的结构如图3-37所示。

可以看到,Employee对象被序列化成了如下XML字符串:

<?xml version="1.0"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Id>12345</Id>
  <Name>Dflying</Name>
  <Email>Dflying@some.com</Email>
  <Salary>2147483647</Salary>
</Employee>

前面曾经提到过,为某个复杂类型中的某个属性添加[System.Web.Script.Serialization.ScriptIgnore]属性可以让ASP.NET AJAX异步

通讯层在自动生成客户端对象时忽略该属性,不过这仅适用于默认的序列化方式,也就是JSON方式。

若希望在XML序列化方式中忽略某复杂对象的某属性,那么我们应该为该属性添加[System.Xml.Serialization.XmlIgnore]属性。

我们还是以忽略Employee类中的Salary属性为例,修改Employee类的实现代码:

private int m_salary;
[System.Xml.Serialization.XmlIgnore]
public int Salary
{
    get { return m_salary; }
    set { m_salary = value; }
}

这时我们再次从客户端调用GetXMLFormatEmployee()这个Web Service方法,将会看到Employee对象被序列化成了如下XML字符串,其中

没有了<Salary />节点:

<?xml version="1.0"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Id>12345</Id>
  <Name>Dflying</Name>
  <Email>Dflying@some.com</Email>
</Employee>

若是某个Web Service方法的返回值为字符串类型,且该Web Service方法将使用XML方式序列化返回值,那么该字符串将被默认为是一个

XML文档的片段,并已XML方式进行序列化。例如如下Web Service方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public string GetString()
{
    string theString = "<persons>"
        + "<person><name>Tom</name><age>30</age></person>"
        + "<person><name>Jerry</name><age>20</age></person>"
        + "</persons>";
 
    return theString;
}

在客户端回调函数中,返回的字符串对象在Visual Studio调试器中显示出的结构如图3-38所示,可以看到原本应该是普通字符串的内容

被当成了XML片断。

ASP.NET AJAX异步通信层在传递数据时默认采用JSON序列化方式,但同时也提供给我们以XML方式进行序列化的选项。本章的最后介绍了

让XML作为客户端和服务器端交互时的数据传递格式的方法。

抱歉!评论已关闭.