3

I am testing out json.net. I would like to use its linq-to-json syntax to return json from a function attributed [WebMethod] but I am getting errors.

For example if I use in the code behind

[WebMethod, ScriptMethod(UseHttpGet = true)]
public static JObject GetStuff() {
    return new JProperty("string", "value");
}

Being called by the following javascript:

  PageMethods.GetStuff(/* parameters */, function(data) {
      // do stuff with data
  });

I get the error "Cannot access child value on Newtonsoft.Json.Linq.JValue".

What should I be returning to ensure that my javascript data object gets filled with JSON?

1 Answer 1

1

Why not simply returning objects and leaving the JSON serialization to the underlying infrastructure:

public class MyModel
{
    public string Value { get; set; }
}

and in your web method:

[WebMethod, ScriptMethod(UseHttpGet = true)]
public static MyModel GetStuff() {
    return new MyModel {
        Value = "some value"
    };
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would rather return pure JSON since the underlying infrastructure is not particularly simple. I also wish to return both a dictionary and an array, where the dictionary will contain frequently occurring items in the array so I can reduce the JSON size.
@sh54, by creating a custom object you will reduce the JSON size because you would include only the properties you need.
Json.Net knows how to handle dictionaries, datatables, etc. as well as other type that the MS serializers choke on... The main reason Json.Net is being included out of the box for the new web api with VS2012/.net 4.5 ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.