views:

1280

answers:

4

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": "[email protected]" } }

To { "name": "bob", email: "[email protected]" }

A: 

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" } }

CL4NCY
+1  A: 

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.

Robert C. Barth
A: 

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.

CL4NCY
+1  A: 

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.

Crescent Fresh
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.
CL4NCY