I have a model in my WebAPI application written in .NET 4.0 that has a type property System.Net.Mime.ContentType, for example:
[Serializable]
public class FileData
{
private ContentType contentType;
private long size;
private string name;
public ContentType ContentType
{
get { return contentType; }
set { contentType = value; }
}
...
}
The model is in a separate assembly from my web project.
So, the client sends me a JSON message that I need to convert to this class:
{
"size": 12345,
"contentType": "image/png",
"name": "avatar.png"
}
To tell Json.NET how to convert ContentType, I registered a user JsonConverterthat I wrote for this purpose:
JsonFormatter.SerializerSettings.Converters.Add(new ContentTypeJsonConverter());
In the above code, I mean the global obeject JsonFormatterfor the WebApi application.
That way, when the client sends me JSON, I expect the controller to parse the message correctly.
Sorry, error failed:
"Cannot convert from System.String to System.Net.Mime.ContentType."
, , FileData:
public class FileData
{
...
[JsonConverter(typeof(ContentTypeJsonConverter))]
public ContentType ContentType { }
}
, JSON.NET , FileData.
ContentType FileData?
, :
JsonFormatter.SerializerSettings.ContractResolver = new CustomResolver();
CustomResolver:
class CustomResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
var contract = base.CreateContract(objectType);
if (objectType == typeof(ContentType))
{
contract.Converter = new ContentTypeJsonConverter();
}
return contract;
}
}
.