3

JavaScriptSerializer を使用して、JSON 文字列から次のクラスのインスタンスを逆シリアル化しようとしています。

public class Filter
{
    public HashSet<int> DataSources { get; set;  }
}

これが私が試しているコードです:

        Filter f = new Filter();

        f.DataSources = new HashSet<int>(){1,2};

        string json = (new JavaScriptSerializer()).Serialize(f);         

        var g= (new JavaScriptSerializer()).Deserialize<Filter>(json);

次のメッセージでエラーになります。

タイプ 'System.Collections.Generic.List 1[System.Int32]' cannot be converted to type 'System.Collections.Generic.HashSet1[System.Int32]' のオブジェクト。

どうやら、シリアライザーは JSON 表現からリストとセットを区別できません。これに対する解決策は何ですか?

注:作業上の制約により、外部ライブラリの使用を避けたいと思います。

4

2 に答える 2

4

これに対する解決策は何ですか?

Json.Netを使用します。このコードは機能します...

Filter f = new Filter();

f.DataSources = new HashSet<int>() { 1, 2 };

string json = JsonConvert.SerializeObject(f);

var g = JsonConvert.DeserializeObject<Filter>(json);

編集

DataContractJsonSerializerも効くらしい…

DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(Filter));
var g2 = dcjs.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json))) as Filter;
于 2013-08-22T13:29:11.363 に答える