Tim Tim - 1 month ago 22
JSON Question

Deserialize Json Array Newtonsoft.Json

I have the following 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"
}
]


I'm trying to deserialize this array and use but I keep getting the following error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'StockTicker.home+Class1' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

Here is my class:

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; }
}


Here is what I'm trying to do:

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

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


I have no idea what to do at this point.

dbc dbc
Answer

As the exception states, your outermost JSON container is an array -- a comma-delimited sequence of values surrounded by [ and ]. As such, it needs to be deserialized into a collection of some sort, as is explained in the docs. Thus you want to do:

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

Sample fiddle.