3

I am trying to determine how to exclude __type in my JSON response from an asmx WebService.

The class that I am returning is constructed as follows.

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() {}
}

I then have a Data Access Layer and Business Logic Layer that returns a populated instance of MyClassName_List. My WebMethod is setup as follows.

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();
    }
}

The JSON object return is structured as follows.

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

I just want to return the JSON object as follows.

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

I have tried the suggestions from here, but I can not seem to implement it properly. Any help on this is much appreciated!

Community
  • 1
  • 1
JoeFletch
  • 3,820
  • 1
  • 27
  • 36

1 Answers1

9

The way to do this is follows.

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() {}
}

I hope this helps someone else too!

JoeFletch
  • 3,820
  • 1
  • 27
  • 36
  • I've been searching for 2 hours, and this answer fixed it in a blip! Thanks! – Stijn Oct 26 '12 at 07:15
  • Glad it helps! Let me know if you have any problems. I have been using this for quite some time now with no issues! – JoeFletch Oct 26 '12 at 11:09
  • Great one thanks ! I had to tackle this problem in VB.net so, for those searching the VB equivalent : `Public Class MyClass Protected Friend Sub New() End Sub End Class` – gis Mar 14 '23 at 14:30