2014-10-02 25 views
1

爲什麼這個JSON反序列化回它從序列化的模型?它將反序列化到一個Bar列表,​​而不是實現List列表的對象。問題反序列化JSON回到原始模型

public class Bars : List<Bar> 
{ 

} 

public class Bar 
{ 
    public decimal Open { get; set; } 
    public decimal High { get; set; } 
    public decimal Low { get; set; } 
    public decimal Close { get; set; } 
} 

private void test() 
{ 
    Bars bars = new Bars() 
    { 
     new Bar(){Open = 1.5269M, High = 1.6001M, Low = 1.4012M, Close = 1.5277M}, 
     new Bar(){Open = 1.5277M, High = 1.6003M, Low = 1.5276M, Close = 1.7008M}, 
     new Bar(){Open = 1.7008M, High = 1.9003M, Low = 1.4276M, Close = 1.60098M} 
    }; 

    JavaScriptSerializer jss = new JavaScriptSerializer(); 

    string json = jss.Serialize(bars); 

    //works 
    var dsBars1 = jss.Deserialize<List<Bar>>(json); 

    //fails 
    var dsBars2 = jss.Deserialize<Bars>(json); 

} 

回答

1

您可以使用Json.Net。下面的代碼工程...

var json = JsonConvert.SerializeObject(bars); 
var dsBars1 = JsonConvert.DeserializeObject<List<Bar>>(json); 
var dsBars2 = JsonConvert.DeserializeObject<Bars>(json);