在字典<double, double[]>中反序列化 JSON。

huangapple go评论124阅读模式
英文:

Deserialize json in Dictionary<double, double[]>

问题

我需要将Dictionary<double, double[]>存储并读取为JSON。到目前为止,我找到的所有链接都处理了Dictionary<object, object>,而不是值为数组的情况。是否有JSON语法可以实现这个,例如:

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

可以反序列化为Dictionary<string, double[]>,但是以下JSON格式是无效的 - 显然。

我是否需要将其保存为嵌套数组,例如:

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

然后手动进行序列化和反序列化转换?

英文:

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

  &quot;MyDic&quot;: {    
  &quot;0&quot;:[90,270],
  &quot;90&quot;:[0],
  &quot;270&quot;:[0]    
  }

deserializes to Dictionary&lt;string,double[]&gt;, but

  &quot;MyDic&quot;: {    
  0:[90,270],
  90:[0],
  270:[0]    
  }

is invalid json - obviously.

Do I need to save it as nested arrays, like

  &quot;MyDic&quot;: [    
  [0,[90,270]],
  [90,[0]],
  [270,[0]]    
  ]

and convert it manually for serializing/deserializing?

答案1

得分: 1

这部分是代码示例,不需要翻译。

英文:

This works OK:

var dict = new Dictionary&lt;double, double[]&gt;()
{
    [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&lt;Dictionary&lt;double, double[]&gt;&gt;(s);

foreach (var entry in dict)
{
    Console.WriteLine($&quot;{entry.Key}: {string.Join(&quot;, &quot;, entry.Value)}&quot;);
}

The output is:

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

And:

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

(Tested with &lt;PackageReference Include=&quot;Newtonsoft.Json&quot; Version=&quot;13.0.3&quot; /&gt;)

What issues are you having?

huangapple
  • 本文由 发表于 2023年7月3日 15:57:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定