1

how to prevent default serialization in a aspnet webform web method (not api or mvc) in order to user Json.net

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

[WebMethod]
public static object MyMethod()
{
     dynamic field1 = new JObject();
     field1.Alessio = "ciao"; 

     return JsonConvert.SerializeObject(field1);        
}

the output is:

{"d":"{\"Alessio\":\"ciao\"}"}

instead it should be

{"d":"{ "Alessio ": "ciao"}"}

because the serialization has been applied twice (from JsonConvert.SerializeObject and from the default serializer)

is there a way to: - disable the default serialization for a single webmethod? or - change the default serializer with Json.Net serializar only on a page or on a method? or - change the default serializer with Json.Net globally?

The project is a webform application (not an api or a mvc application) and is not intended to move WebMethods on a WCF or on a HttpHandler

1
  • Your desired output is not valid JSON. Did you mean {"d": { "Alessio": "ciao" } } instead? Commented Oct 17, 2016 at 15:10

1 Answer 1

4

I made the webmethod "void" (in order to prevent automatic serialization) and set the correct http headers by hand/manually craft the Response:

[WebMethod]
public static void MyMethod()
{
    .....
    ...
    ..
    string result = JsonConvert.SerializeObject(_d);
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ContentType = "application/json";
    HttpContext.Current.Response.AddHeader("content-length", result.Length.ToString());                HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.Write(result);
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's the only way to override the default serializer for page and asmx methods that I know of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.