omri_saadon
omri_saadon

Reputation: 10671

Serialize dictionary into json file

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).

Upvotes: 3

Views: 9923

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

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"
    }
  }
}

Upvotes: 1

Related Questions