Reputation: 139
I have the following json :
[
{
"Key": "tradepack",
"Value": [
"Select Tradepack"
]
},
{
"Key": "route",
"Value": [
"Select Route"
]
},
{
"Key": "recall",
"Value": [
"Select Recall Location"
]
},
{
"Key": "stones",
"Value": [
"True"
]
},
{
"Key": "quickstep",
"Value": [
"True"
]
},
{
"Key": "dreamingdonkey",
"Value": [
"True"
]
},
{
"Key": "meleeskills",
"Value": []
},
{
"Key": "rangedskills",
"Value": []
},
{
"Key": "buffedskills",
"Value": []
}
]
Im currently using this
String data = System.IO.File.ReadAllText(Application.StartupPath + "\\folder\\Data\\Config\\config.txt");
return JsonConvert.DeserializeObject<Dictionary<string, object[]>>(data);
but i get the following error
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Object[]]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1.
Anyone care to explain as how i would solve this im a newb in c# especially serialization
Upvotes: 0
Views: 2782
Reputation: 15364
Your json is an array/list. So you need to deserialize to something like this List<Dictionary<string, object>>
var data = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);
OR
var dict = JArray.Parse(json)
.Select(x => x.ToObject<KeyValuePair<string, string[]>>())
.ToDictionary(x => x.Key, x => x.Value);
Upvotes: 3
Reputation: 3112
Your data looks more like a KeyValuePair<string, string[]>[]
. You can try deserializing to that, then creating a dictionary based on the result.
var kvps = JsonConvert.DeserializeObject<KeyValuePair<String, String[]>[]>(data);
return kvps.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);
Upvotes: -1