How to set the StreamingContext for DataContractSerializer?

ぃ、小莉子 提交于 2020-01-03 13:10:06

问题


I have some code something like this:

[DataContract]
class Foo {
    [OnSerializing]
    private void BeforeSerialize(StreamingContext ctx)
    {
        ((MtType)ctx.Context).DoStuff()
    }

    ...
}

var reader = new XmlTextReader(filename);
var serializer = new DataContractSerializer(typeof(Type));
Type type = (Type)serializer.ReadObject(reader);

and I need to provide the StreamingContext structure. I have found several references that this can be done for NetDataContractSerializer but none for DataContractSerializer.

  • Is there a way to make this work?
  • Am I just doing this wrong?

回答1:


The use of IDataContractSurrogate lets you do custom JSON serialization and deserialization on a per-type or per-object basis.

See IDataContractSurrogate Methods for the API docs and see DataContract Surrogate for the sample.

Also, to read and interpret JSON, you would start with JsonReaderWriterFactory, not an XML factory. See JsonReaderWriterFactory Class to see what I mean.

Hope this helps!



来源:https://stackoverflow.com/questions/687088/how-to-set-the-streamingcontext-for-datacontractserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!