Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Dictionary <-> JSON

Dictionary <-> JSON

Scheduled Pinned Locked Moved C#
jsonquestionlearning
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    softwarejaeger
    wrote on last edited by
    #1

    Hello, is there any possible and simple way to convert a Dictionary to a JSON-String an of course to convert it in the other direction (JSON-String to Dictionary)? I've searched a lot, but i havent't found a simple solution. Thank you

    L 1 Reply Last reply
    0
    • S softwarejaeger

      Hello, is there any possible and simple way to convert a Dictionary to a JSON-String an of course to convert it in the other direction (JSON-String to Dictionary)? I've searched a lot, but i havent't found a simple solution. Thank you

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      You can use Json.NET[^] for the same. However, I have found one class which converts Dictionary to String that might help you.

      class ConvertDictionary
      {
      Dictionary<string, int> _dictionary = new Dictionary<string, int>()
      {
      {"salmon", 5},
      {"tuna", 6},
      {"clam", 2},
      {"asparagus", 3}
      };

      public ConvertDictionary()
      {
          // Convert dictionary to string and save
          string s = GetLine(\_dictionary);
          File.WriteAllText("dict.txt", s);
          // Get dictionary from that file
          Dictionary<string, int> d = GetDict("dict.txt");
      }
      
      string GetLine(Dictionary<string, int> d)
      {
          // Build up each line one-by-one and them trim the end
          StringBuilder builder = new StringBuilder();
          foreach (KeyValuePair<string, int> pair in d)
          {
              builder.Append(pair.Key).Append(":").Append(pair.Value).Append(',');
          }
          string result = builder.ToString();
          // Remove the final delimiter
          result = result.TrimEnd(',');
          return result;
      }
      
      Dictionary<string, int> GetDict(string f)
      {
          Dictionary<string, int> d = new Dictionary<string, int>();
          string s = File.ReadAllText(f);
          // Divide all pairs (remove empty strings)
          string\[\] tokens = s.Split(new char\[\] { ':', ',' },
              StringSplitOptions.RemoveEmptyEntries);
          // Walk through each item
          for (int i = 0; i < tokens.Length; i += 2)
          {
              string name = tokens\[i\];
              string freq = tokens\[i + 1\];
      
              // Parse the int (this can throw)
              int count = int.Parse(freq);
              // Fill the value in the sorted dictionary
              if (d.ContainsKey(name))
              {
                  d\[name\] += count;
              }
              else
              {
                  d.Add(name, count);
              }
          }
          return d;
      }
      

      }

      HTH

      Jinal Desai - LIVE Experience is mother of sage....

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups