2016-11-08 134 views
0

我有以下的JSON反序列化JSON數組Newtonsoft.Json

[ 
{ 
    "id":"656332", 
    "t":"INTU", 
    "e":"NASDAQ", 
    "l":"108.35", 
    "l_fix":"108.35", 
    "l_cur":"108.35", 
    "s":"2", 
    "ltt":"4:00PM EST", 
    "lt":"Nov 8, 4:00PM EST", 
    "lt_dts":"2016-11-08T16:00:01Z", 
    "c":"+0.45", 
    "c_fix":"0.45", 
    "cp":"0.42", 
    "cp_fix":"0.42", 
    "ccol":"chg", 
    "pcls_fix":"107.9", 
    "el":"108.43", 
    "el_fix":"108.43", 
    "el_cur":"108.43", 
    "elt":"Nov 8, 4:15PM EST", 
    "ec":"+0.08", 
    "ec_fix":"0.08", 
    "ecp":"0.08", 
    "ecp_fix":"0.08", 
    "eccol":"chg", 
    "div":"0.34", 
    "yld":"1.26" 
}, 
{ 
    "id":"13756934", 
    "t":".IXIC", 
    "e":"INDEXNASDAQ", 
    "l":"5,193.49", 
    "l_fix":"5193.49", 
    "l_cur":"5,193.49", 
    "s":"0", 
    "ltt":"4:16PM EST", 
    "lt":"Nov 8, 4:16PM EST", 
    "lt_dts":"2016-11-08T16:16:29Z", 
    "c":"+27.32", 
    "c_fix":"27.32", 
    "cp":"0.53", 
    "cp_fix":"0.53", 
    "ccol":"chg", 
    "pcls_fix":"5166.1729" 
} 
] 

我試圖反序列化數組和使用,但我不斷收到以下錯誤:

不能反序列化JSON當前陣列(例如[1,2,3])類型爲'StockTicker.home + Class1',因爲類型需要JSON對象(例如{「name」:「value」})才能正確反序列化。

這裏是我的類:

public class Rootobject 
    { 
     public Class1[] Property1 { get; set; } 
    } 

    public class Class1 
    { 
     public string id { get; set; } 
     public string t { get; set; } 
     public string e { get; set; } 
     public string l { get; set; } 
     public string l_fix { get; set; } 
     public string l_cur { get; set; } 
     public string s { get; set; } 
     public string ltt { get; set; } 
     public string lt { get; set; } 
     public DateTime lt_dts { get; set; } 
     public string c { get; set; } 
     public string c_fix { get; set; } 
     public string cp { get; set; } 
     public string cp_fix { get; set; } 
     public string ccol { get; set; } 
     public string pcls_fix { get; set; } 
     public string el { get; set; } 
     public string el_fix { get; set; } 
     public string el_cur { get; set; } 
     public string elt { get; set; } 
     public string ec { get; set; } 
     public string ec_fix { get; set; } 
     public string ecp { get; set; } 
     public string ecp_fix { get; set; } 
     public string eccol { get; set; } 
     public string div { get; set; } 
     public string yld { get; set; } 
    } 

這裏是我想要做的事:

var jsonObject1 = JsonConvert.DeserializeObject<Rootobject>(json); 

var blah = jsonObject1.Property1[0].c; 

我不知道在這一點上做的。

回答

1

作爲例外狀態,最外層的JSON容器是一個數組 - 逗號分隔的數值序列,由[]包圍。因此,需要將其反序列化爲某種集合,如docs中所解釋的。因此,你想做的事:

var items = JsonConvert.DeserializeObject<Class1 []>(json); 
var blah = items[0].c; 

樣品fiddle

+0

謝謝你的例子和解釋......總的意義。 – Tim