Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Make Json.NET the Default Json Serializer

If I have a web service (.asmx) and I want it to use Json.NET to serialize all the objects that I return from that web service, is there a way to do that?

In other words, I have a class like this:

    [JsonObject(MemberSerialization.OptOut)]
    public partial class Person
    {
        public string FirstName {get; set;}

        public string LastName {get; set;}

        [JsonIgnore]    
        public string Password {get; set;}    
    }

And in my web service, I have this:

    [WebMethod]
    public Person GetBlahPerson()
    {
        Person p = new Person();
        p.FirstName = "bob";
        p.LastName = "smith";
        p.Password = "don't tell";

        return p;
    }

If using jQuery I set the return type to json, it serializes my object to json.

Is it possible to make it use Json.net through a setting in web.config or something similar?

like image 470
Micky McQuade Avatar asked Aug 23 '10 21:08

Micky McQuade


1 Answers

Just JSON -- no. You are only able to redefine the whole IHttpHandlerFactory using

<add verb="*" path="*.asmx" type="YourScriptHandlerFactory" validate="false"/>

But this will mean that you will need to either fall back to default implementation using reflection, or implement your analog of System.Web.Script.Services namespace (that is quite large).

I actually did it with reflection fallbacks for other purpose (centralized error handling), so it should be possible, but it requires precision and would be very brittle between .NET releases.

Do you use classic ASP.NET or MVC? If you use MVC, just use a controller, it is so much easier.

like image 78
Andrey Shchekin Avatar answered Oct 20 '22 04:10

Andrey Shchekin