【问题标题】:Serialising and deserialising a JSON object returned by an ASP.Net web service对 ASP.Net Web 服务返回的 JSON 对象进行序列化和反序列化
【发布时间】:2010-11-17 00:04:22
【问题描述】:

我有一个简单的 ASP.Net Web 服务/脚本方法,它返回一个 JSON 对象,然后在回发期间对其进行修改并发送回页面 - 我需要能够反序列化这个对象:

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,但是MyClass 需要同时实现IXmlSerializable 和ISerializable,并且包含在单独的程序集中 -我提到这一点是因为到目前为止这些都给我带来了问题。

我该怎么做? (使用标准的 .Net 类型或使用 JSON.Net 之类的东西)

【问题讨论】:

    标签: asp.net json serialization


    【解决方案1】:

    您可以使用 System.Web.Extensions 中的 JavaScriptSerializer 类来反序列化 JSON 字符串。例如,以下代码将 hash 转换为 .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】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        相关资源
        最近更新 更多