C# serializer/deserializer with same functionality as XStream in java -
i need accomplish simple task: serialize , deserialize object hierarchy.
i've tried xmlserializer
, datacontractserializer
, netdatacontractserializer
nothing seems work, there problem.
xmlserializer
bad because requires properties public. (net)datacontractserializer(s) bad because it's missing metadata - there no metadata when user creates xml.
so how solve task? consider classes:
class { private b instanceb; private int integervalue; ... getters/setters } class b { private list<c> cinstancelist; private string stringvalue; ... getters/setters } class c { ... other properties ... getters/setters }
and user input:
<a> <b> <cinstancelist> <c> <someproperties>val</someproperties> </c> <c> <someproperties>differentval</someproperties> </c> </cinstancelist> <strigvalue>lalala<stirngvalue> </b> <integervalue>42</integervalue> </a>
what datacontractors
missing metadata "type" or "namespace" etc. xstream
doesn't need that. know type of deserializing object, need write function:
public t deserialize<t>(string xml);
my wanted use case:
var mydeserializedobject = deserialize<a>(inputstring);
what doing wrong? solve differently?
no serializer fix typing mistakes ;). worked me using datacontractserializer xml (text.xml)
<a> <b> <cinstancelist> <c> </c> <c> </c> </cinstancelist> <stringvalue>lalala</stringvalue> </b> <integervalue>42</integervalue> </a>
classes
[datacontract(namespace="")] class { [datamember(name = "b")] private b instanceb; [datamember(name = "integervalue")] private int integervalue; public a(b instanceb, int integervalue) { this.instanceb = instanceb; this.integervalue = integervalue; } } [datacontract(namespace = "")] class b { [datamember(name = "cinstancelist")] private list<c> cinstancelist; [datamember(name = "stringvalue")] private string stringvalue; public b(list<c> cinstancelist, string stringvalue) { this.cinstancelist = cinstancelist; this.stringvalue = stringvalue; } } [datacontract(namespace = "")] class c { }
read
var dcs = new datacontractserializer(typeof(a)); using (stream reader = file.openread("text.xml")) { var result = (a)dcs.readobject(reader); }
if write add xmlns:i="http://www.w3.org/2001/xmlschema-instance" won't make difference remove if need to.
Comments
Post a Comment