C# json Webservice 包装在 XML 中

本文关键字:XML 包装 json Webservice | 更新日期: 2023-09-27 18:30:24

这是一个生成 json 的 C# Web 服务,但它包装在 XML 中。 有什么简单的方法可以在服务器端代码上解决此问题吗? 这是一个简单的网站解决方案。我的 web.config 中可能缺少某些内容吗?

非常感谢。

更新:由于某种原因,这里的答案之一消失了,但这是一个很好的建议,我不要序列化和重新运行 json 对象。我不知道该怎么做。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService
{
    public WebService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    DataClassesDataContext dc = new DataClassesDataContext();

[WebMethod]
    public string GetID(string id)
    {

        var json = "";
        var uid = from result in dc.GET_ID(id) select result;
        JavaScriptSerializer jss = new JavaScriptSerializer();
        json = jss.Serialize(uid);
        return json;
    }

C# json Webservice 包装在 XML 中

删除的答案建议首先使用ScriptMethodScriptService属性(即 [ScriptMethod(UseHttpGet = false, ResponseFormat=ResponseFormat.Json)] )。

这是从 .NET 中的 Web 服务返回 json 的正确方法。

有关详细信息,请参阅此处:如何让 ASMX 文件输出 JSON。