简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM