0

I have a WebMethod like this one:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Event> getEvents()
{
    var db = new DbContext();
    var events = from x in db.Event select x;

    return events.ToList();
}

By default it use JsonSerializer from .NET i want to use Json.Net as default serializer it is possible?

It isn't a WFC project, it's a Website project in Visual Studio.

Mattia Rossi
  • 175
  • 13
  • it's not WCF project – Mattia Rossi May 27 '16 at 09:47
  • Does this answer help? [How to get JSON response from a 3.5 asmx web service](https://stackoverflow.com/questions/19563641/how-to-get-json-response-from-a-3-5-asmx-web-service/19564022#19564022). You would replace `Context.Response.Write(js.Serialize(data));` with `Context.Response.Write(JsonConvert.SerializeObject(events));`. – dbc May 29 '16 at 21:52

1 Answers1

0

If you've got Json.net already then you just need to ensure you have the using statement and you can just return the json string:

string json = JsonConvert.SerializeObject(events.ToList());
return json;

This should do it.

Percy
  • 2,855
  • 2
  • 33
  • 56
  • 1
    this not work. because the default serializer serialize the string returned from `JsonConvert.SerializeObject` – Mattia Rossi May 27 '16 at 10:08
  • Try removing the line `[ScriptMethod(ResponseFormat = ResponseFormat.Json)]` – Percy May 27 '16 at 10:43
  • your return type should be `string`. – Percy May 27 '16 at 10:43
  • I have to remove `[ScriptMethod(ResponseFormat = ResponseFormat.Json)]` try but it serialize to XML – Mattia Rossi May 27 '16 at 10:50
  • ah - you must be requesting as XML - you'll need to specify json in the request. you'll need `Content-Type:application/json` in the header – Percy May 27 '16 at 10:57
  • Yeah i know, but without `[ScriptMethod(ResponseFormat = ResponseFormat.Json)]` it alway return XML, when the `Content-Type` setted. – Mattia Rossi May 27 '16 at 11:01
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/113134/discussion-between-rick-and-cronos). – Percy May 27 '16 at 11:02
  • You can prevent the xml serialization with: [ScriptMethod(ResponseFormat = ResponseFormat.Xml, UseHttpGet = false, XmlSerializeString = false)] – Chris Lukic Mar 27 '18 at 16:22