英文:
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<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?
答案1
得分: 1
这部分是代码示例,不需要翻译。
英文:
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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论