2010-11-17 49 views
1

我有一個簡單的ASP.Net web服務/腳本方法,它返回一個JSON對象,然後在回發期間將其修改併發送回頁面 - 我需要以能夠deserialise此目的:對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需要implemnt既IXmlSerializableISerializable,並且包含在一個單獨的大會 - 我提到這一點,因爲迄今爲止這些都給我造成了問題。

我該怎麼做? (使用標準的.Net類型或使用類似JSON.Net的東西)

回答

0

您可以使用System.Web.Extensions中的JavaScriptSerializer類來反序列化JSON字符串。例如,下面的代碼轉換散列成.NET Dictionary對象:

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 
0

JavaScriptSerializer是靜態頁面方法使用序列化他們的反應類,所以它也是什麼適用於對特定JSON進行反序列化:

protected void myButton_OnClick(object sender, EventArgs e) 
{ 
    string json = myHiddleField.Value; 

    MyClass obj = new JavaScriptSerializer().Deserialize<MyClass>(json); 
}