2010-11-17 47 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); 
}