1

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

1 Answer 1

3

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")
Sign up to request clarification or add additional context in comments.

2 Comments

I thought it was due to that and I hoped it can be replaced. thanks for your reply. Anyway I think I'll switch to web.api because i need to validate and save an anonymous object and I need the features of JObject
Yes, I would definitely recommend switching to Web API if you can. ASMX is quite outdated now and is not very extensible, e.g. it does not have an easy way to replace the serializer that I know of.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.