Search code examples
c#jsonjson-deserialization

Deserializing JSON with dynamic keys into certain type


I want to deserialize a JSON string into an Version object with the help of Newtonsoft.Json.

History is a dictionary of int keys and TaskObject values. The key is a dynamic number.

Here is a short example of the JSON:

[
   {
     "CurrentVersion": 3,
     "TaskObject": {},
     "History": {
       "1": {},
       "2": {}
     },
     "ObjectTypeName": "the type"
   }
]

My Class

public class Version : Lib.Objects.Task
    {
        public int CurrentVersion { get; set; }
        public Lib.Objects.Task TaskObject { get; set; }
        public Dictionary<int, Lib.Objects.Task> History { get; set;} 
        public string ObjectTypeName { get; set; }                          
    }

Code

string rawJSON;
using (var wc = new WebClient())
    rawJSON = wc.DownloadString(uri);
var version = JsonConvert.DeserializeObject<Objects.Version>(rawJSON); //throws a JsonSerializationException

But I get an exception

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

Any ideas how to fix this, so I can deserialize the JSON to a Version object?

Edit

Turning out that I was receiving a JSON array, so I've edited my example.


Solution

  • I've found a solution:

    string rawJSON;
    using (var wc = new WebClient())
        rawJSON = wc.DownloadString(uri);
    
    var versions = new List<Objects.Version>();
    foreach (var jToken in JArray.Parse(rawJSON))
        versions.Add(JsonConvert.DeserializeObject<Objects.Version>(jToken.ToString()));