3

i am trying to serialize a dictionary into json and it does not work for me.

this is my dictionary:

public Dictionary<string, Dictionary<string, string>> roaming = new Dictionary<string,Dictionary<string, string>>();

and this is how i tried to serialize it:

string json = JsonConvert.SerializeObject(this.client); // the dictionary is inside client object
//write string to file
System.IO.File.WriteAllText(@"path", json);

am i doing that wrong? (for members of type int or string it's working just fine).

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • possible duplicate of [Serialize .NET Dictionary into JSON Key Value Pair Object](http://stackoverflow.com/questions/5124889/serialize-net-dictionarystring-string-into-json-key-value-pair-object) – Paul Zahra Aug 20 '14 at 13:05

1 Answers1

1

Works fine for me, may be an issue with Library version or data contained therein. Here's what I was able to get working:

Simple "Client" class (just doing some simple translations given your nested dictionary set):

public class Client
{
    public Dictionary<string, Dictionary<string, string>> roaming
    {
        get { return this._roaming ?? (this._roaming = new Dictionary<string, Dictionary<string, string>>()); }
        set { this._roaming = value; }
    }
    private Dictionary<string, Dictionary<string, string>> _roaming;


    public Client()
    {
        this.roaming.Add("en", new Dictionary<string, string> {
            { "login", "login" },
            { "logout", "logout" },
            { "submit", "submit" }
        });
        this.roaming.Add("sp", new Dictionary<string, string> {
            { "login", "entrar" },
            { "logout", "salir" },
            { "submit", "presentar" }
        });
    }
}

Then, instantiate and serialize:

Client client = new Client();
String json = JsonConvert.SerializeObject(client, Newtonsoft.Json.Formatting.Indented);

And the [expected] result:

{
  "roaming": {
    "en": {
      "login": "login",
      "logout": "logout",
      "submit": "submit"
    },
    "sp": {
      "login": "entrar",
      "logout": "salir",
      "submit": "presentar"
    }
  }
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200