This is my first question on stackoverflow - so far I've always found a solution here :)
I am trying to deserialise JSON object. The problem is the 'count' list, because elements may change - name and value. I think it's best to use the Dictionary for this - but the compiler throws errors.
{
"count": [
{"apple": 2},
{"strawberry": 8},
{"pear": 2}
],
"on_plate": true,
"owner": "Billy"
}
my c# class:
public class FruitsDTO
{
public Dictionary<string, int> count { get; set; }
public bool on_plate{ get; set; }
public string owner{ get; set; }
}
var respResponse = JsonConvert.DeserializeObject<FruitsDTO>(jsonObject);
and result: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Int32]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
EDITED
Thanks @Phuzi and @Prasad Telkikar :)
I change class to:
public class FruitsDTO
{
public Dictionary<string, int> count { get; set; }
public Dictionary<string, int> Count2
{
get => Count.SelectMany(x => x).ToDictionary(x => x.Key, x => x.Value);
}
public bool on_plate{ get; set; }
public string owner{ get; set; }
}
Count2 - that's exactly what i need.
bool_plate - it's just a typo when renaming in the correct class for the sake of this example