【问题标题】:Deserialize JSON Object with JSON.NET使用 JSON.NET 反序列化 JSON 对象
【发布时间】:2010-07-03 08:20:02
【问题描述】:

我在这里遇到了一个问题,我真的找不到能够在 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”, “参数”:[ { “姓名”:“约翰”, “职位”:“首席技术官” } ] } }​', contentType: "应用程序/json; charset=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 ;







}

非常感谢。

【问题讨论】:

    标签: json asp.net-ajax


    【解决方案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 的属性中,而不是引用 Dictionary 键。

    【讨论】:

      【解决方案2】:

      我不确定我是否遵循您的代码(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 字符串,它可以将其反序列化为它所代表的类的实例。

      【讨论】:

      • 非常感谢您的回复,Jobject 是来自客户端的 json,我只是想要访问 Json 值而不是将它们转换为对象,例如我只想访问名称值或大小数组
      • 您正在发布一个 JSON string,这是正确的,所以我不确定您的方法为什么接受 JObject 类型的东西。我认为在不先将其转换为对象的情况下说要“访问 Json 值”是没有意义的。就我所知,这种弱类型的数据结构是你可以在 JavaScript 中做的,而不是 C#。您是否尝试像问题标题所暗示的那样使用 Newtonsoft Json.NET?
      • 非常感谢您为我解释 :)
      【解决方案3】:

      按照您的示例代码,如果您在客户端执行以下 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 });
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        • 2013-07-25
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        相关资源
        最近更新 更多