skip to Main Content

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.List1[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


  1. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array

    Not sure if it will work but you can try that

    JsonArrayAttrribute Usage in C# Code ( Json.Net )

    Login or Signup to reply.
  2. Your root json element is array, so the data can be represented as collection of Dictionary<string, JToken>:

    var result = JsonConvert.DeserializeObject<List<Dictionary<string, JToken>>>(json);
    

    But I suggest to introduce a class representing data and processing it correspondingly:

    public class Root
    {
        [JsonProperty("key")]
        public string Key { get; set; }
    
        [JsonProperty("value")]
        public List<string> Value { get; set; }
    }
    
    Root myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(json);
    
    Login or Signup to reply.
  3. you can extract data as a dictionary

    Dictionary<string,List<string>> dic = JArray.Parse(json)
        .ToDictionary(k=> (string) k["key"], k=> k["value"].ToObject<List<string>>());
    

    but since you have a collection , it is more natural to extract the data as a collecton

    List<KeyValuePair<string,List<string>>> list = JsonConvert.DeserializeObject<List<KeyValuePair<string,List<string>>>>(json);
        
        //how to use
        
    List<string> cod2 = list.Where(l =>l.Key=="cod2").FirstOrDefault().Value; 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search