treeden
treeden

Reputation: 755

Json Object deserialize to a List<class>

I have a Json string containing arrays and a single key with a value as you can see below.

{
"MSG": "Hallo Stackoverflow!",
"0": {
    "ID": "2",
    "Subject": "Danish",
    "Message": "Message",
    "DateEnd": "2016-02-28 00:00:00"
},
"1": {
    "ID": "2",
    "Subject": "Math",
    "Message": "Message",
    "DateEnd": "2016-02-29 00:00:00"
}}

I pass this to a JObject to get the MSG value, then remove it from the json. However, when key is gone, the numbers of the array gets deleted and I cannot pass it through my code:

JObject data = JObject.Parse(json);
string MSG = data["MSG"].ToString();
data.Remove("MSG"); 
List<HomeWork> homework = JsonConvert.DeserializeObject<List<HomeWork>>(json);

I get an error:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Memento.HomeWork]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

If I generate it as an array without the key, it works fine.

Upvotes: 1

Views: 1297

Answers (1)

Matias Cicero
Matias Cicero

Reputation: 26281

You are actually trying to deserialize a JSON object rather than a JSON array.

Note that the following would be a JSON array (and you would be able to deserialize it into a List<Homework>):

[{
    "ID": "2",
    "Subject": "Danish",
    "Message": "Message",
    "DateEnd": "2016-02-28 00:00:00"
},
{
    "ID": "2",
    "Subject": "Math",
    "Message": "Message",
    "DateEnd": "2016-02-29 00:00:00"
}]

In order to deserialize this JSON object, you must use a Dictionary<TKey, TValue> (because you don't know the object's keys beforehand), which in your case is Dictionary<int, Homework>:

Dictionary<int, Homework> homeworks = JsonConvert.DeserializeObject<Dictionary<int, Homework>>(json);

Homework hw = homeworks[0]; //This will be your first homework, the one with ID = 2

Upvotes: 1

Related Questions