c# - ICollection<T> Why SerializationBinder is call on HashSet<T> but not on List<T> -
i have object :
public class mycollec { public icollection<myobject> mycollection { get; set; } public mycollec() { mycollection = new list<myobject>(); } }
in webapi had serializationbinder, in webapiconfig :
jsonformatter.serializersettings.binder = new defaultserializationbinder();
when call controller return object structure this
{ "mycollection": [ { ... }, { ... } ] }
but if change constructor hashset
public mycollec() { mycollection = new hashset<myobject>(); }
the result of controller :
{ "mycollection": { "$type": "system.collections.generic.hashset`1[[webapplication1.models.myobject, webapplication1]], system.core", "$values": [ { ... }, { ... } ] } }
i understand why ? difference induce behavior ?
is-it possible use hashset give same result list ?
edit :
@grundy comment :
typenamehandling property auto , doc: include .net type name when type of object being serialized not same declared type. seems hashset serialized not same declared type.
it's true, it's reason, why it's not true list ? type different of icollection hashset...
moreover, try change typenamehandling property there no option set $type on inherited objects...
http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_typenamehandling.htm
thanks @grundy clue.
i keep
jsonformatter.serializersettings.typenamehandling = typenamehandling.auto;
and had custom jsonconverter change serialization of hashset
public class hashsetarrayconverter : jsonconverter { public override void writejson(jsonwriter writer, object value, jsonserializer serializer) { ienumerable collectionobj = (ienumerable)value; writer.writestartobject(); foreach (object currobj in collectionobj) { serializer.serialize(writer, currobj); } writer.writeendobject(); } public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { return serializer.deserialize(reader, objecttype); } public override bool canconvert(type objecttype) { var canconvert = isassignabletogenerictype(objecttype, typeof(hashset<>)); return canconvert; } private static bool isassignabletogenerictype(type giventype, type generictype) { var interfacetypes = giventype.getinterfaces(); if (interfacetypes.any(it => it.isgenerictype && it.getgenerictypedefinition() == generictype)) { return true; } if (giventype.isgenerictype && giventype.getgenerictypedefinition() == generictype) return true; type basetype = giventype.basetype; if (basetype == null) return false; return isassignabletogenerictype(basetype, generictype); } }
and add in config :
jsonformatter.serializersettings.converters.add(new hashsetarrayconverter());
Comments
Post a Comment