3

基本的に私は を含む を持ってDataContractいますDictionary:

[DataContract]
public class MyDictionary : IDictionary<string, object> {
    [DataMember(Name = "Data")]
    protected IDictionary<string, object> Dictionary { get; private set; }

    // ...
}

XML 出力の関連部分を次に示します。

<Data>
 <a:KeyValueOfstringanyType>
  <a:Key>ID</a:Key>
  <a:Value i:type="s:int">2</a:Value>
 </a:KeyValueOfstringanyType>
 <a:KeyValueOfstringanyType>
  <a:Key>Value</a:Key>
  <a:Value i:type="s:int">4711</a:Value>
 </a:KeyValueOfstringanyType>
</Data>

出力を次のように簡略化するにはどうすればよいですか。

<Data>
  <ID i:type="s:int">2</ID>
  <Value i:type="s:int">4711</Value>
</Data>

ディクショナリ キーは文字列に制限されているため、ASCII 以外のキーを使用するというばかげた考えを誰も得なければ、正常に機能するはずです。CollectionDataContract必要なものに少し近づいた属性を見つけましたが、キーと値のペアが完全に保存され、メモリが浪費されます。多分それはクラスを愛することは可能ISerializableですが、それがDataContractSerializer. ちなみに、このソリューションはDataContractJsonSerializer.

4

1 に答える 1

1

あなたが抱えている問題は、IDictionary<'string, object> が (ある意味で) IEnumerable<'KeyValuePair<'string, object>> であるという事実から生じています。これは、DataContractSerializer が各 KeyValuePair の個性をシリアル化する方法です。

あなたが求めているのは (私が正しく理解している場合)、カスタムのシリアル化を作成することであり、そのためにIXmlSerializableインターフェイスを実装できます。

WriteXml 関数と ReadXml 関数を使用して、パラメーターとして渡された XmlWriter でストリームに書き込まれる xml を制御します。

たとえば、この関数

public void WriteXml(XmlWriter writer)
    {
        foreach (var pair in _dictionary)
        {
            writer.WriteElementString("Key", pair.Key);
            writer.WriteElementString("Value", pair.Value.ToString());
        }
    }

この結果が得られます

<MyDictionary xmlns="http://schemas.datacontract.org/2004/07/Sandbox">
    <Key>ID</Key>
    <Value>15</Value>
    <Key>Value</Key>
    <Value>123</Value>
</MyDictionary>

2 つのペアがディクショナリに入力されていると仮定します (ID,15 & 値, 123)。

ああ、JSON については、IJsonSerializableがありますが、それを使用することはできませんでした。

于 2013-05-11T16:19:15.870 に答える