Search code examples
c#jsonserializationdeserializationjson-deserialization

Deserialize json in Dictionary<double, double[]>


I need to store and read a Dictionary<double, double[]> in json. All links I found so far handles Dictionary<object,object>, not the case where the value is an Array. Is there a json-Syntax for this, like:

  "MyDic": {    
  "0":[90,270],
  "90":[0],
  "270":[0]    
  }

deserializes to Dictionary<string,double[]>, but

  "MyDic": {    
  0:[90,270],
  90:[0],
  270:[0]    
  }

is invalid json - obviously.

Do I need to save it as nested arrays, like

  "MyDic": [    
  [0,[90,270]],
  [90,[0]],
  [270,[0]]    
  ]

and convert it manually for serializing/deserializing?


Solution

  • This works OK:

    var dict = new Dictionary<double, double[]>()
    {
        [0] = new double[] { 0, 1, 2 },
        [1] = new double[] { 3, 4, 5 },
        [2] = new double[] { 6, 7, 8 }
    };
    
    string s = JsonConvert.SerializeObject(dict, Formatting.Indented);
    
    Console.WriteLine(s);
    
    dict = JsonConvert.DeserializeObject<Dictionary<double, double[]>>(s);
    
    foreach (var entry in dict)
    {
        Console.WriteLine($"{entry.Key}: {string.Join(", ", entry.Value)}");
    }
    

    The output is:

    {
      "0": [
        0.0,
        1.0,
        2.0
      ],
      "1": [
        3.0,
        4.0,
        5.0
      ],
      "2": [
        6.0,
        7.0,
        8.0
      ]
    }
    

    And:

    0: 0, 1, 2
    1: 3, 4, 5
    2: 6, 7, 8
    

    (Tested with <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />)

    What issues are you having?