2011-02-09 61 views
3

我試圖通過Silverlight反序列化從JavaScript返回的json。從JSON(ScriptObject)反序列化到託管對象

基本上在客戶端,我返回JSON和我的C#的處理程序,我通過ScriptObject得到它...

我試圖在ScriptObject中的ConvertTo方法,仍然無法得到任何東西。

我將如何能夠將ScriptObject轉換爲一個C#對象,它是一個對象列表?

SomeCallBack(ScriptObject result) { 

    // convert to managed object 

    var objects = result.ConvertTo<List<SomeObjectClass>>(); // can't get any property from it.. 

    // however the count is correct... 
    MessageBox.Show("count: " + objects.Count); // shows correct count of items 
} 

回答

1

Silverlight中不包含API採取ScriptObject和序列化到JSON字符串。

Silverlight支持通過在System.ServiceModel.Web dll中找到的System.Runtime.Serialization.Json.DataContractJsonSerializer類的JSON序列化。

您將需要獲得一些基於JavaScript的JSON串行器,將您試圖通過的值轉換爲ScriptObject,以便傳遞JSON字符串參數而不是ScriptObject。我相信這個工作的流行工具是JQuery。

現在看起來您正在等待一組(JSON如「[x1,x2 ,,, xn]」),其中x項的類型爲SomeObjectClass。你可以用這個小的通用功能deserialise這樣的列表: -

List<T> DeserializeJSON<T>(string json) 
    { 

     byte[] array = Encoding.UTF8.GetBytes(json); 
     MemoryStream ms = new MemoryStream(array); 

     DataContractJsonSerializer dcs = new DataContractJsonSerializer(typeof(List<T>)); 
     return (List<T>)dcs.ReadObject(ms); 

    } 

你會做: -

var objects = DeserializeJSON<SomeObjectClass>(someJSON); 
0

如果您要返回實際的JSON對象,那麼您實際上可以使用ScriptObject.ConvertTo方法將JSON對象直接反序列化爲C#對象。例如,你可以這樣做:

JSON對象

{ id: 0001, 
    name: 'some_name', 
    data: [0.0, 1.0, 0.9, 90.0] } 

C#對象

using System.Runtime.Serialization; // From the System.Runtime.Serialization assembly 

[DataContract] 
public struct JsonObj 
{ 
    [DataMember] 
    public int id; 

    [DataMember] 
    public string name; 

    [DataMember] 
    public double[] data; 
} 

C#回調

public void SomeCallback(ScriptObject rawJsonObj) 
{ 
    // Convert the object 
    JsonObj jsonObj = rawJsonObj.ConvertTo<JsonObj>(); 
} 

但是,如果要返回一個表示JSON對象的字符串,而不是實際的JSON對象,那麼這將不起作用,您將不得不使用另一種反序列化方法。有關更多詳細信息,請參閱MSDN

希望這會有所幫助。

0

我得到它只是通過模仿 JS對象由C#代碼。有趣的是,它甚至允許在JS方面使用對象文字(參見Collection項目,它們只是對象文字 - 很好的舉動 - 實際上JS是驅動程序!)。

SL代碼(我通過JS對象到我SL組件,用於處理):

[ScriptableMember()] 
public string GetValue(ScriptObject o) 
{ 

    Prototype p = (Prototype)o.ConvertTo<Prototype>(); 
    return "A"; 
} 

JS:

control.Content.ExternalName.GetValue({ Collection: [{ a: "A1" }, { a: "A2"}] }) 

C#

public class Prototype 
{ 
    public List<PrototypeItem> Collection 
    { 
    get; 
    set; 
    } 
} 

public class PrototypeItem 
{ 
    public string a 
    { 
    get; 
    set; 
    } 
}