How to set the StreamingContext for DataContractSerializer?
Asked Answered
T

1

6

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?
Totem answered 26/3, 2009 at 18:51 Comment(0)
A
0

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!

Autoplasty answered 3/2, 2011 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.