你可以使用JsonConvert.PopulateObject() http://www.newtonsoft.com/json/help/html/PopulateObject.htm相反,当哈希集是根对象时:
var newH = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
JsonConvert.PopulateObject(s, newH);
当哈希集为not根对象,如果预先分配,Json.NET 将填充它,除非ObjectCreationHandling.Replace http://www.newtonsoft.com/json/help/html/DeserializeObjectCreationHandling.htm已启用。这允许包含类型使用所需的比较器预先分配哈希集,例如:
public class RootObject
{
public RootObject() { this.Collection = new HashSet<string>(StringComparer.OrdinalIgnoreCase); }
public HashSet<string> Collection { get; private set; }
}
或者,您可以子类化CustomCreationConverter<HashSet<T>> http://www.newtonsoft.com/json/help/html/DeserializeCustomCreationConverter.htm并使用转换器内所需的比较器分配哈希集Create() http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Converters_CustomCreationConverter_1_Create.htm method:
public class HashSetCreationConverter<T> : CustomCreationConverter<HashSet<T>>
{
public IEqualityComparer<T> Comparer { get; private set; }
public HashSetCreationConverter(IEqualityComparer<T> comparer)
{
this.Comparer = comparer;
}
public override HashSet<T> Create(Type objectType)
{
return new HashSet<T>(Comparer);
}
}
然后执行以下操作:
var newH = JsonConvert.DeserializeObject<HashSet<string>>(s, new HashSetCreationConverter<string>(StringComparer.OrdinalIgnoreCase));