Background: We are using an attribute that changes the output of the response to a JSON object when certain headers are passed. Another attribute returns XML when the appropriate accept header is passed. If the accept header is missing or “html”, a test page is returned.
I need to be able to serialize an object structure like this:
[DataContract]
public class ResponseModel
{
[DataMember]
public bool Success { get; set;}
[DataMember]
public dynamic Data { get; set; } //I have tried "Object" as well
[DataMember]
public ApiErrorModel Error { get; set; }
}
//for reference
[DataContract]
public class ApiErrorModel
{
[DataMember]
public string ErrorCode { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
}
The problem I’m having is while I haven’t been able to test any error states yet, when it goes to serialize a structure like this:
[DataContract]
public class DatabaseModel
{
[DataMember]
List<Database> Database { get; set; }
//snip implementation
}
[DataContract]
public class Database
{
[DataMember]
[Required]
public string DatabaseName { get; set; }
[DataMember]
List<Guid> APITokens { get; set; }
//snip other fields..., Guids and strings...
}
It fails, giving me the error:
Type ‘[namespace].Api.Business.Web.Models.DatabaseModel’ with data contract name ‘DatabaseModel:http://schemas.datacontract.org/2004/07/%5Bnamespace%5D.Api.Business.Web.Models’ 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 have researched using a DataContractResolver, but I can’t seem to get it to work with the JSON version of it. It may be easier to switch to JSON.NET or JavaScriptSerializer serializer, but it needs to work for XML as well (This might be a JSON-specific issue). I’m wondering if there’s a way to fix this without adding every type of list I’m going to use to the serialization method list of known types.
JSON.NET is basically the way to go. It seems the DataContractJsonSerializer isn’t up for the task.