[英]Deserializing a string into a dictionary that contains an object
我有一個這樣聲明的字典:
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);
還是不行。
有任何想法嗎?
因此,您正在嘗試將一些具體的 class 轉換為自定義 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);
Output
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}]
注意:此答案專門涉及如何將具體的 class 轉換為數組(並返回),您需要如何格式化數據(什么順序)不是這個答案的關注點,我將把這些細節留給你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.