代码之家  ›  专栏  ›  技术社区  ›  DevMania

用JSON.NET反序列化JSON对象

  •  0
  • DevMania  · 技术社区  · 14 年前

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

    “呼叫”:{ “参数”:[ { “Name”:“约翰”, “Position”:“首席技术官” } ] } }', contentType:“应用程序/json;字符集=utf-8“, 数据类型:“json”, 是的,

                    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 回复  |  直到 14 年前
        1
  •  1
  •   Dave Ward    14 年前

    如果在输入参数上指定匹配类型,page方法将自动反序列化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的属性中,而不是引用字典键。

        2
  •  1
  •   JustinStolle    14 年前

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

    一串

        3
  •  1
  •   JustinStolle    14 年前

    遵循示例代码,如果在客户机上执行以下jqueryjavascript(将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 });
      }
    }