1

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.

treeden
  • 675
  • 1
  • 6
  • 17
  • Possible duplicate of [Deserialize json with known and unknown fields](http://stackoverflow.com/questions/15253875/deserialize-json-with-known-and-unknown-fields) , especially http://stackoverflow.com/a/21763919/3745022 – Eugene Podskal Mar 05 '16 at 13:51
  • Stack trace tells you that JSON object with '0', '1', ... as keys is not the same as JSON array. You should probably treat your collection as a dictionary. – MarengoHue Mar 05 '16 at 13:57

1 Answers1

1

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
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • Thanks Matias for the answer. I see what you meant by the Json array and the Dictionary. I found a solution and it works as it should. I have been trying over an hour with no solution, thanks again! – treeden Mar 05 '16 at 14:49