Home > Enterprise >  JsonSerializer.Deserialize to 2D Dictionary
JsonSerializer.Deserialize to 2D Dictionary

Time:12-30

I try to deserialize the following up json example to a 2D Dictionary. I was searching for a solution in the www first and stackoverflow. I found many solutions for 1D and also answers for declaring the 2D Dictionary, like Dictionary<string, Dictionary<string, string>>

The string from File.ReadAllText(path) is read successful and correct with JsonSerializer.Deserialize<myObject>(mystrWithJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) (tested with breakpoint in Visual Studio)

I use System.Text.Json

My Json-File looks like that:

{
  "One" : {
    "OneOne" : "a directory path",
    "OneTwo" : "a directory path"
  },
  "Two" : {
    "TwoOne" : "a directory path",
    "TwoTwo" : "a directory path"
  }
  "Three" : {
    "ThreeOne" : "a directory path",
    "ThreeTwo" : "a directory path"
  }

My Class looks like that:

public class TwoDimDictionary
{
    public IDictionary<string, IDictionary<string, string>> DirectoryPaths { get; set; }
    
    public DirectoryEnviroment(IDictionary<string, IDictionary<string, string>> directoryPaths)
    {
        DirectoryPaths = directoryPaths;
    }
}

The main task is that the program will add or remove entries. So "VS -> Edit -> Paste Special -> Json" will not help me in that case. The entries will be saved as .json file, if the program closes. The code is running, but the object is null, so it will be the System.NullReferenceException: Object reference not set to an instance of an object.

Any idea or is just my json format wrong?

CodePudding user response:

try this code using System.Text.Json

var dict= System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, Dictionary<string,string>>>(json);
  
string twoOne=dict["Two"]["TwoOne"];

result

a directory path TwoOne

and you have to fix your json

{
  "One": {
    "OneOne": "a directory path",
    "OneTwo": "a directory path"
  },
  "Two": {
    "TwoOne": "a directory path TwoOne",
    "TwoTwo": "a directory path"
  },
  "Three": {
    "ThreeOne": "a directory path",
    "ThreeTwo": "a directory path"
  }
}

if you want to use your class , try this code

var dict= new TwoDimDictionary( 
JsonSerializer.Deserialize<Dictionary<string, Dictionary<string,string>>>(json));

 var twoOne=dict.DirectoryPaths["Two"]["TwoOne"];

public class TwoDimDictionary
{
    public Dictionary<string, Dictionary<string, string>> DirectoryPaths { get; set; }

    public  TwoDimDictionary(Dictionary<string, Dictionary<string, string>> directoryPaths)
    {
        DirectoryPaths = directoryPaths;
    }
}
  • Related