1

我正在创建一个 C# ASP.NET Web 服务应用程序。我需要从 SQL 数据库访问数据并将这些数据作为 XML 或 JSON 返回。当您运行 HelloWorld 方法(参见下面的代码)时,它会以 XML 格式返回数据。但我需要从 SQL 数据中制作自己的 XML 标记。这是怎么做到的?

此外,如何让 Web 服务使用 JSON,而不是 XML?

例如,假设我从 SQL 返回一个包含 2 行和 2 列的表集,并将其格式化为 XML:

<returnSet>
  <row1>
    <FirstName>
      David
    </FirstName>
    <LastName>
      Faustino
    </LastName>
  </row1>
  <row2>
    <FirstName>
      Henry
    </FirstName>
    <LastName>
      Irons
    </LastName>
  </row2>
</returnSet>

非常感谢您提供的任何帮助。

更新

我修改了下面的代码以包含返回的 JSON。问题是当我调试应用程序并单击该方法时,它仍然显示 XML:

<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://tempuri.org/">"Hello World"</string>

我的期望是编写下面的代码,然后转到 Debug => Start Debugging。单击HelloWorld,瞧,它以 JSON 的形式返回数据。我在其他地方看到有些人使用 jQuery 或纯 JavaScript 调用它。这是测试它返回 JSON 数据的唯一方法吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

namespace WebApplication2
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string HelloWorld()
        {

            JavaScriptSerializer js = new JavaScriptSerializer();

            return js.Serialize("Hello World");
        }
    }
}
4

1 回答 1

1

您可以在 HelloWorld 方法的 [WebMethod] 下方添加另一个属性来获取 json:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
于 2013-01-28T07:43:28.880 回答