【问题标题】:asp.net 2.0 asmx WebService Exclude __type in JSON Responseasp.net 2.0 asmx WebService 在 JSON 响应中排除 __type
【发布时间】:2012-05-31 20:24:26
【问题描述】:

我正在尝试确定如何在来自 asmx WebService 的 JSON 响应中排除 __type

我返回的类构造如下。

public class MyClassName
{
    private string _item1 = string.Empty;
    private string _item2 = string.Empty;

    public string item1 = { get { return _item1; } set { _item1 = value; } }
    public string item2 = { get { return _item2; } set { _item2 = value; } }
}

public class MyClassName_List : List<MyClassName>
{
    public MyClassName_List() {}
}

然后我有一个数据访问层和业务逻辑层,它返回一个填充的MyClassName_List 实例。我的 WebMethod 设置如下。

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyClassName_WebService : System.Web.Services.WebService
{
    [WebMethod]
    public MyClassName_List GetList()
    {
        return MyClassName_List_BusinessLogicLayer.GetList();
    }
}

JSON 对象返回的结构如下。

[
    {
    item1: "item1-1 text",
    item2: "item1-2 text",
    __type: "NamespaceUsed.MyClassName"
    },
    {
    item1: "item2-1 text",
    item2: "item2-2 text",
    __type: "NamespaceUsed.MyClassName"
    },
]

我只想返回JSON对象如下。

[
    {
    item1: "item1-1 text",
    item2: "item1-2 text"
    },
    {
    item1: "item2-1 text",
    item2: "item2-2 text"
    }
]

我已经尝试了here 的建议,但我似乎无法正确实施。非常感谢您提供任何帮助!

【问题讨论】:

    标签: asp.net json web-services asp.net-ajax


    【解决方案1】:

    方法如下。

    public class MyClassName
    {
        private string _item1 = string.Empty;
        private string _item2 = string.Empty;
    
        public string item1 = { get { return _item1; } set { _item1 = value; } }
        public string item2 = { get { return _item2; } set { _item2 = value; } }
    
        protected internal MyClassName() { } //add a protected internal constructor to remove the returned __type attribute in the JSON response
    }
    
    public class MyClassName_List : List<MyClassName>
    {
        public MyClassName_List() {}
    }
    

    我希望这对其他人也有帮助!

    【讨论】:

    • 我已经搜索了 2 个小时,这个答案很快就解决了!谢谢!
    • 很高兴它有帮助!如果您有任何问题,请告诉我。我已经使用了很长时间了,没有任何问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2013-07-27
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多