views:

81

answers:

3

hi, 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.

+1  A: 

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.

JustinStolle
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?
JustinStolle
Thanks a lot for explaining it for me :)
+1  A: 

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 });
  }
}
JustinStolle
thanks for showing me another way to do it :)
+1  A: 

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.

Dave Ward
this is the simplest i was looking for thanks alot man :)

related questions