Question

I'm running into an issue using System.Runtime.Serialization.Json.DataContractJsonSerializer to serialize a List<T> of proxied objects. It works fine with a single proxied object, but the List makes it blow up. Something like this:

using System.Collections.Generic;
using System.Runtime.Serialization;
using Castle.DynamicProxy;
using System.IO;
using NUnit.Framework;

[DataContract] 
public class SimpleViewModel 
{ 
    [DataMember] 
    public virtual int ID { get; set; } 
} 
[Test] 
public void TestSerializeArray() 
{ 
    // Generates a proxy of type "SimpleViewModelProxy"
    var proxyModel = (new ProxyGenerator()).CreateClassProxy<SimpleViewModel>(); 
    proxyModel.ID = 1; 
    //Put it into List<> (it can handle a single item without issue!) 
    var list = new List<SimpleViewModel> { proxyModel }; 
    var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<SimpleViewModel>)); 
    using (var stringWriter = new MemoryStream()) 
    { 
        serializer.WriteObject(stringWriter, list); //BOOM CRASH! 
    } 
} 

Doing this gives me the following exception:

System.Runtime.Serialization.SerializationException : Type 'Castle.Proxies.SimpleViewModelProxy' with data contract name 'SimpleViewModelProxy:http://schemas.datacontract.org/2004/07/ Castle.Proxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

I'm able to serialize either a single "SimpleViewModelProxy" object, or a List<SimpleViewModel>, but not a List<SimpleViewModelProxy>. Has anyone had any experience getting this to work? Can they provide some pointers on what I'm doing wrong?

Was it helpful?

Solution

You can try to add the type of the proxy to the list of known types:

var serializer = new DataContractJsonSerializer(
    typeof(List<SimpleViewModel>),
    new[] { proxyModel.GetType() });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top