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

序列化和反序列化ASP.Net web服务返回的JSON对象

  •  1
  • Justin  · 技术社区  · 15 年前

    public class MyWebPage : Page
    {
        [WebMethod]
        [ScriptMethod]
        public static MyClass MyWebMethod()
        {
            // Example implementation of my web method
            return new MyClass() 
            {
                MyString = "Hello World",
                MyInt = 42,
            };
        }
    
        protected void myButton_OnClick(object sender, EventArgs e)
        {
            // I need to replace this with some real code
            MyClass obj = JSONDeserialise(this.myHiddenField.Value);
        }
    }
    
    // Note that MyClass is contained within a different assembly
    [Serializable]
    public class MyClass : IXmlSerializable, ISerializable
    {
        public string MyString { get; set; }
        public int MyInt { get; set; }
        // IXmlSerializable and ISerializable implementations not shown
    }
    

    我可以对这两种web方法进行更改 MyWebMethod MyClass 然而 两者都需要实现 IXmlSerializable ISerializable ,并包含在一个单独的程序集中-我之所以提到这一点,是因为到目前为止这些都给我带来了问题。

    我该怎么做?(可以使用标准的.Net类型,也可以使用类似JSON.Net的内容)

    2 回复  |  直到 15 年前
        1
  •  0
  •   Maksym Kozlenko    15 年前

    您可以使用System.Web.Extensions中的JavaScriptSerializer类来反序列化JSON字符串。例如,以下代码将哈希转换为.NET字典对象:

    using System;
    using System.Collections.Generic;
    using System.Web.Script.Serialization;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var dict = new JavaScriptSerializer().Deserialize<Dictionary<string,int>>("{ a: 1, b: 2 }");
                Console.WriteLine(dict["a"]);
                Console.WriteLine(dict["b"]);
                Console.ReadLine();
            }
        }
    }
    

    代码输出为:

    1
    2
    
        2
  •  0
  •   Dave Ward    15 年前

    JavaScriptSerializer是静态页面方法用来序列化其响应的类,因此它也是反序列化特定JSON的合适对象:

    protected void myButton_OnClick(object sender, EventArgs e)
    {
        string json = myHiddleField.Value;
    
        MyClass obj = new JavaScriptSerializer().Deserialize<MyClass>(json);
    }
    
    推荐文章