使用JSON.NET反序列化JSON对象

时间:2010-07-03 08:20:03

标签: json asp.net-ajax

我在这里面临一个问题,我真的找不到能够在web方法中删除我的后续JSON对象的值的方法

ASPX代码

     $(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: '{

“致电”:'{     “类型”:“U”,     “Params”:[       {         “名字”:“约翰”,         “职位”:“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代码

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





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







}

非常感谢先进。

3 个答案:

答案 0 :(得分:1)

我不确定我是否遵循您的代码(您的类是JObject?),但如果您使用的是Json.NET(如您的问题所述),请查看序列化示例(来自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);

给定一个Json 字符串,它可以将其反序列化为它所代表的类的实例。

答案 1 :(得分:1)

按照示例代码,如果在客户端上执行以下jQuery JavaScript(将contentType保留为默认值);

$(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);
      }

    });
  });
});

你可以在服务器端做这样的事情,假设使用Json.NET(在http://json.codeplex.com/找到),但你必须将你的字符串反序列化为一个对象:

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 });
  }
}

答案 2 :(得分:1)

如果在输入参数上指定匹配类型,页面方法将自动为您反序列化JSON。根据您的示例数据字符串,如下所示:

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"];
}

我在那里使用了一本字典,因为你提到了灵活性。如果Params是可预测的,那么您可以使用正式类型而不是词典。然后,您可以“点”到Param的属性中,而不是引用字典键。