Thursday, March 24, 2011

Returning a JSON object from a PageMethod with custom formating

Is it possible to format how an object is returned as JSON from a PageMethod? ie. removing the first "d" element from the data, without writing the JSON from scratch.

From { "d": { "name": "bob", "email": "bob@bob.com" } }

To { "name": "bob", email: "bob@bob.com" }

From stackoverflow
  • A simple example would be:

    public class User {
        public string name;
    }    
    
    [WebMethod]
    public static User getUser() {
    
        User u = new User();
        u.name = "Bob";
    
        return u;
    
    }
    

    returns { "d": { "name": "Bob" } }

  • No. Microsoft's JSON serializer adds the d for some reason on the server side, and the client-side AJAX code that deserializes the JSON string expects it to be there.

  • My particular scenario involves ExtJS forms which load configuration data via a .NET handler. The JSON received by these forms needs to be a specific format. At the moment I'm building the response manually and it would be better to use the built-in JSON serializers of .NET.

  • The extra "d" parameter is added by the .NET framework as an added security measure against XSS attacks [source]. It's included when the "Content-Type" of the request specifies "application/json".

    I think you can get the framework to exclude it (ie don't wrap the result in the "d") if you simply specifying the "Content-Type" of the request as something other than "application/json". Try removing that header from the request (if you can) and seeing what .NET returns.

    CL4NCY : Unfortunately you have to use this content-type to return data as JSON, anything else just doesn't work. I think I need to look at this problem form another angle, ie. getting ExtJS to accept JSON in this format. Thanks.

0 comments:

Post a Comment