OrderedDictionary
私はint
のキーとSystem.Drawing.Rectangle
の値を持っています。 JSON.NETはOrderedDictionary
をシリアル化しません...空のオブジェクトを返します。私はカスタムコンバーターを書いたが、もっと簡単な方法があるのか疑問に思った。 JSON.NETはDictionary<TKey, TValue>
のシリアライズとデシリアライズのための内蔵のコードを使用するトリガとして型付けされた列挙子の存在を使用するかもしれないことを考えると、私はこれを試してみました:OrderedDictionaryでJSON.NETを使用
class Program
{
static void Main(string[] args)
{
var test = new OrderedDictionary<int, Rectangle>();
test.Add(1, new Rectangle(0, 0, 50, 50));
test.Add(42, new Rectangle(1, 1, 1, 1));
string s = JsonConvert.SerializeObject(test);
var deserialized = JsonConvert.DeserializeObject<OrderedDictionary<int, Rectangle>>(s);
var someRect = deserialized[(object)1]; // someRect is null
var someOtherRect = (Rectangle)deserialized["1"]; // InvalidCastException
}
}
public class OrderedDictionary<TKey, TValue> : OrderedDictionary, IEnumerable<KeyValuePair<TKey, TValue>>
{
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
foreach (TKey key in Keys)
{
yield return new KeyValuePair<TKey, TValue>(key, (TValue)this[key]);
}
}
}
シリアライゼーション完璧に動作します。ただし、逆シリアル化すると、辞書のキーは文字列になり、Rectangle
はに変換できないJObject
です。 OrderedDictionary<>
クラスにJSON.NETで適切なデシリアライズを追加できるものがありますか?ありがとう。
「System.Collections.Specialized」のどれですか? – Eser
はい。私は15文字を使用しなければならないので、私は[この記事](http://stackoverflow.com/questions/2629027/no-generic-implementation-of-ordereddictionary)を読んで、良い実装の1つを考えていますそこでは、同じ非直列化の動作を恐れています。 –
JSON.NETはこれをまだサポートしていない可能性があります。この質問を投稿するにはhttps://github.com/JamesNK/Newtonsoft.Json –