我有一个这样声明的字典:
IDictionary<string, Rectangle> myitems = new Dictionary<string, Rectangle>();
// Populate with items
myitems["aaa"] = new Rectangle(10, 20, 30, 40);
myitems["bbb"] = new Rectangle(13, 34, 13, 232);
我可以通过这样做来序列化它:
string MyDictionaryToJson(IDictionary<string, Rectangle> dict)
{
var entries = dict.Select(d =>
string.Format(""{0}": [{1}]", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";
}
String serializedItems = MyDictionaryToJson(myitems);
我的问题是,我找不到相反的方法,无法将序列化的字符串转换回进入我的字典。我试着不使用任何额外的库,但我甚至在尝试过这个之后:
Dictionary<string, Rectangle> mynewdic = JsonConvert.DeserializeObject<Dictionary<string, Rectangle>>(myitems);
仍然不起作用。
有什么想法吗?
因此,您正在尝试将一些具体类转换为自定义json数组。
通常使用JsonConverter
给定
public class RectangleConverter : JsonConverter<Rectangle>
{
public override void WriteJson(JsonWriter writer, Rectangle value, JsonSerializer serializer)
{
var array = new JArray {value.X, value.Y, value.Top, value.Bottom};
array.WriteTo(writer);
}
public override Rectangle ReadJson(JsonReader reader, Type objectType, Rectangle existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var s = JArray.Load(reader);
return new Rectangle(int.Parse(s[0].ToObject<string>()),int.Parse(s[1].ToObject<string>()),int.Parse(s[2].ToObject<string>()),int.Parse(s[3].ToObject<string>()));
}
}
示例用法
var myitems = new Dictionary<string, Rectangle>();
myitems["aaa"] = new Rectangle(10, 20, 30, 40);
myitems["bbb"] = new Rectangle(13, 34, 13, 232);
Console.WriteLine("Original Dictionary");
foreach (var item in myitems)
Console.WriteLine(item);
var json = JsonConvert.SerializeObject(myitems, Formatting.Indented, new RectangleConverter());
Console.WriteLine();
Console.WriteLine("Serialized data");
Console.WriteLine(json);
var result = JsonConvert.DeserializeObject<Dictionary<string, Rectangle>>(json, new RectangleConverter());
Console.WriteLine();
Console.WriteLine("Recreated Dictionary");
foreach (var item in result)
Console.WriteLine(item);
输出
Original Dictionary
[aaa, {X=10,Y=20,Width=30,Height=40}]
[bbb, {X=13,Y=34,Width=13,Height=232}]
Serialized data
{
"aaa": [
10,
20,
30,
40
],
"bbb": [
13,
34,
13,
232
]
}
Recreated Dictionary
[aaa, {X=10,Y=20,Width=30,Height=40}]
[bbb, {X=13,Y=34,Width=13,Height=232}]
注意:这个答案专门讨论如何将具体类转换为数组(然后再转换回来(,如何需要格式化数据(顺序(不是这个答案的问题,我将把这些细节留给你