开发者

Interfaces and JSON Serialization in .Net

Is there any JSON library for .Net that allows me to serialize/deserialize classes containing interfaces:

 public class MyClass
 {
    public IMyInterface1 Property1 {get;set;}
    public IMyInterface2 Property2 {get;set;}
 }

I realize concrete classes will be necessary for deserialization, so I'm assum开发者_如何学编程ing they would need to be specified through attributes or as part of the method call.

Edit: One additional requirement - It should not rely on any markers or special properties on the JSON for serialization/deserialization, as sometimes I'll need to read JSON from a 3rd party.


Managed do do this using jayrock. You just need to create a mapping class like this one:

public class InterfaceImporter<TInterface, TClass> : IImporter where TClass : TInterface
{
    public object Import(ImportContext context, JsonReader reader)
    {
        return(context.Import<TClass>(reader));
    }

    public Type OutputType
    {
        get { return (typeof(TInterface)); }
    }
}

Then use this code to map the interfaces to the appropriate classes and deserialize:

ImportContext context = new ImportContext();

context.Register(new InterfaceImporter<IMyInterface1, MyClass1>());
context.Register(new InterfaceImporter<IMyInterface2, MyClass2>());

MyClass deserialized = context.Import<MyClass>(JsonText.CreateReader(json));


You could use the DataContractJsonSerializer class which allows you to work with known types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜