-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Description
I was trying to deserialize a list of JSON arrays into a list of custom types, however since the arrays contained different types (strings and ints) I had to deserialize into a list of objects.
This however created objects that I could not cast into their appropriate types. (I got a "Cannot cast 'o[0]' (which has an actual type of 'object') to 'string'" Error)
The solution was to deserialize the response data using newtonsoft's JsonConvert directly into a temporary model (List<List>) and then map the array values to properties in the constructor of the Torrent class below.
Is there a better solution to converting a JSON array of values into an object model?
The JSON looks like this:
"torrents": [
["3CBD049351C6AA2FC691C4C2430BF09DB856F627",136,"Test Torrent",13169258503,1000,13208580103,1320779776,99,0,0,0,"",0,0,0,0,65536,-1,0],
["AFF58B68FFD50ED2FEB26F3B48861E018C0D7FE6",136,"Test Torrent 2",4035379511,1000,4063772983,406339584,99,0,0,0,"",0,0,0,0,65536,-1,0]
]
The end-goal model looks like this:
public List torrents { get; set; }
public class Torrent
{
public string hash { get; set; }
public int status { get; set; }
public string name { get; set; }
public int size { get; set; }
public int percentProgress { get; set; }
public int downloaded { get; set; }
public int uploaded { get; set; }
public int ratio { get; set; }
public int uploadSpeed { get; set; }
public int downloadSpeed { get; set; }
public int eta { get; set; }
public string label { get; set; }
public int peersConnected { get; set; }
public int peersInSwarm { get; set; }
public int seedsConnected { get; set; }
public int seedsInSwarm { get; set; }
public int availability { get; set; }
public int torrentQueueOrder { get; set; }
public int remaining { get; set; }
}