0

i am facing a problem here, i really could not find a way to be able to strip out the values of my following JSON Object in a web method

ASPX Code

     $(document).ready(function () {
        // Add the page method call as an onclick handler for the div.
        $("#Button1").click(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/MethodCall",
                data: '{

"Call" : '{ "Type" : "U", "Params" : [ { "Name" : "John", "Position" : "CTO" } ] } }​', contentType: "application/json; charset=utf-8", dataType: "json", cache: true,

                success: function (msg) {
                    // Replace the div's content with the page method's return.
                    $("#Result").text(msg.d);
                },
                error: function (xhr, status, error) {
                    // Display a generic error for now.
                    var err = eval("(" + xhr.responseText + ")");

                    alert(err.Message);
                }

            });
        });
    });

ASPX.CS Code

 [WebMethod]
public static string MethodCall(JObject Call)
{





   return "Type of call :"+ Call.Type + "Name is :" + Call.Params.Name + "Position is :"
    Call.Params.Position ;







}

thanks a lot in advanced.

3 Answers 3

1

The page method will automatically deserialize JSON for you if you specify a matching type on the input parameter. Based on your example data string, something like this:

public class CallRequest
{
  public string Type;
  public Dictionary<string, string> Params;
}

public static string MethodCall(CallRequest Call)
{
  return "Type of call: " + Call.Type + 
         "Name is: " + Call.Params["Name"] + 
         "Position is: " + Call.Params["Position"];
}

I used a dictionary there because you mentioned flexibility. If the Params are predictable, you could use a formal type there instead of the Dictionary. Then, you could "dot" into Param's properties instead of referencing Dictionary keys.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure I follow your code (is JObject your class?), but if you're using Json.NET (as your question states), have a look at the Serialization Example (from http://james.newtonking.com/projects/json-net.aspx):

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Given a Json string, it can deserialize it into an instance of the class it represents.

3 Comments

thanks alot fo hte reply, the Jobject is the json comming from client side, what i simply want is to access the Json values and not convert them to an Object like fro example i just want to access the Name Value, or the Sizes array
You're posting a JSON string, which is proper, so I'm not sure why your method is accepting something of type JObject. I don't think it makes sense to say you want to 'access the Json values' without first converting it to an object. That sort of weakly-typed data structure is something you can do in JavaScript, not C# as far as I know. Are you attempting to use Newtonsoft Json.NET as the question title implies?
Thanks a lot for explaining it for me :)
1

Following your example code, if you do the following jQuery JavaScript on the client (leave contentType as default);

$(document).ready(function() {
  // Add the page method call as an onclick handler for the div.
  $("#Button1").click(function() {
    $.ajax({
      type: "POST",
      url: "Default.aspx/MethodCall",
      data: { call: '{ "Type": "U", "Params": { "Name": "John", "Position": "CTO"} }' },
      //contentType: "application/x-www-form-urlencoded",
      dataType: "json",
      cache: true,
      success: function(msg) {
        // Replace the div's content with the page method's return.
        $("#Result").text(msg.d);
      },
      error: function(xhr, status, error) {
        // Display a generic error for now.
        var err = eval("(" + xhr.responseText + ")");

        alert(err.Message);
      }

    });
  });
});

you could potentially do something like this on the server-side, assuming use of Json.NET (found at http://json.codeplex.com/), but you have to deserialize your string into an object:

using Newtonsoft.Json;

public class JsonMethodCallObject {
  public string Type { get; set; }
  public System.Collections.Hashtable Params { get; set; }
}

[WebMethod]
public static string MethodCall(string call) {
  try {
    JsonMethodCallObject deserializedObject = JsonConvert.DeserializeObject<JsonMethodCallObject>(call);
    return JsonConvert.SerializeObject(new {
      d = "Type of call: " + deserializedObject.Type +
        ", Name is: " + deserializedObject.Params["Name"] +
        ", Position is: " + deserializedObject.Params["Position"]
    });
  } catch (Exception ex) {
    return JsonConvert.SerializeObject(new { d = ex.Message });
  }
}

Comments

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.