I have in following string:
[{"key":"cod1","value":["RR4","RR6"]},{"key":"cod2","value":["RR2","RR3"]},{"key":"cod3","value":["RR1","RR2"]}]and I want to save it in a dictionary like this:
Dictionary<string, List>
The project is made in C# and to try to do it I use the following statement:
Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(ss);
But I get this error:
"Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type ‘System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List
1[System.String]]’ because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.rnTo 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.rnPath ”, line 1, position 1.rn at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract)rn at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)rn at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)rn at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)rn at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)rn at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)rn at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)rn at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)rn at operationWebAPI.Repository.TransferLadleRepository.LastEvents() in C:UsersraulmDocumentosProyectosSOSteelShopBackendoperationWebAPIRepositoryTransferLadleRepository.cs:line 1164rn at operationWebAPI.Controllers.TransferLadleController.GetLastEvents() in C:UsersraulmDocumentosProyectosSOSteelShopBackendoperationWebAPIControllersTransferLadleController.cs:line 229"
I can’t find how to solve the problem. Can you help me? Thanks a lot!!
3
Answers
Not sure if it will work but you can try that
JsonArrayAttrribute Usage in C# Code ( Json.Net )
Your root json element is array, so the data can be represented as collection of
Dictionary<string, JToken>
:But I suggest to introduce a class representing data and processing it correspondingly:
you can extract data as a dictionary
but since you have a collection , it is more natural to extract the data as a collecton