Search code examples
c#jsonjson.net

c# Dictionary to Json and Dictionary to Dictionary, how?


I trying to do Dictionary with access as dictionary["1"] -> "Some":

public static Dictionary<string, string> dictionary { get; private set; } = new();
string json = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary);

json ={
  "1": "Some",
  "2222": "Data",
  "4123": "In",
  "107": "That",
  "4213213": "Json"
}

after, I want read it:

string fileContents = sr.ReadToEnd();
dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(fileContents);

and getting error:

Newtonsoft.Json.JsonSerializationException: "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' 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"})

I tried:

string json = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary.ToArray());

with json output

[
  {
    "Key": "1",
    "Value": "Some"
  },
  {
    "Key": "2222",
    "Value": "Data"
  }
]

and after

dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(fileContents);

getting the same error. Where Is a mistake?


Solution

  • Check what contains string fileContents= sr.ReadToEnd(); IMHO You have a bug there, the file must be contains the previous json or a corrupted text.

    After you fix it , then for the second case instead of a dictionary it is more efficient to use a KeyValuePair list

    var list = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(json);
    

    or you can still use a dictionary, but only a list of dictionaries

    var dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject< List<Dictionary<string, string>>>(json);