giammin
giammin

Reputation: 18958

Empty JSON.NET JObject from Asp.net WebMethod

I'm struggling in returning a JSON.NET JObject from an Asp.net WebMethod (no MVC or Web.API).

I dont want to use a string instead of a JObject and i need to use anonymous object so I cant map it to a know class.

this is a stripped down version of the code:

Asp.net WebMethod:

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class DataRoomService : WebServiceBase
{
    [WebMethod(EnableSession = true)]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
    public JObject Load(int id)
    {
            var rtn = new
            {
                Gender = true,
                Age = 56,
                Weigth = 102.4,
                Date = DateTime.Now.AddDays(-7)
            };
            return JObject.FromObject(rtn);
    }

jQuery ajax request:

$.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: url,
    data: input === '' ? '{}' : input,
    async: useasync,
    success: function (data) {
        ...
    }, ...

result: "{"d":[[[]],[[]],[[]],[[]]]}"

Upvotes: 1

Views: 443

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129697

The problem is that ASMX web services use the JavaScriptSerializer internally, which doesn't know how to serialize a JObject. But you don't really need to use a JObject here at all-- just change your web method to return object and return the anonymous object directly:

public object Load(int id)
{
    var rtn = new
    {
        Gender = true,
        Age = 56,
        Weight = 102.4,
        Date = DateTime.Now.AddDays(-7)
    };
    return rtn;
}

Note that the JavaScriptSerializer serializes dates in Microsoft format ("\/Date(1497023008910)\/") instead of ISO 8601 ("2017-06-16T15:56:05Z"). If you need ISO 8601, you'll need to make sure to format the date manually in the anonymous object before returning it:

       Date = DateTime.UtcNow.AddDays(-7).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssK")

Upvotes: 3

Related Questions