【转】C# WebAPI中为自定义模型设置JSonConverter
我的WebAPI應用程序中有一個模型,用.NET 4.0編寫,含有一個System.Net.Mime.ContentType類型的屬性,如下所示:
?
[Serializable] public class FileData {private ContentType contentType;private long size;private string name;public ContentType ContentType{get { return contentType; }set { contentType = value; } }.../* same getter/setter logic for the other fields */ }該模型的定義位于我的Web項目的另一個程序集中.
所以,客戶端發給我一個JSON消息,我需要轉換為這個類:
?
{"contentType": "image/png","size": 12345,"name": "avatar.png" }為了告訴Json.NET如何轉換ContentType,我注冊了一個自定義的JsonConverter:
?
JsonFormatter.SerializerSettings.Converters.Add(new ContentTypeJsonConverter());在上面的代碼中,我指的是WebApi應用程序的全局JsonFormatter對象.
因此,當客戶端向我發送JSON時,我希望控制器能夠正確地解析消息.
不幸的是,它失敗并出現錯誤:
?
“Could not cast or convert from System.String to System.Net.Mime.ContentType.”
我知道我可以通過將以下代碼添加到我的FileData類來解決這個問題:
?
public class FileData {...[JsonConverter(typeof(ContentTypeJsonConverter))]public ContentType ContentType { /* Getter and Setter */ } }但問題是我不能在FileData類型所在的程序集中向JSON.NET引入依賴項.
有沒有辦法在不改變FileData類的情況下觸發contentType成員的正確反序列化?
除了以上我還嘗試了Brian Rogers建議:
?
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;} }結果仍然相同.
最佳答案 以下適用于我(Web API 2).
模型:
?
[Serializable] public class FileData {private ContentType contentType;public ContentType ContentType{get { return contentType; }set { contentType = value; }} }自定義JSON轉換器:
?
public class ContentTypeJsonConverter : JsonConverter {public override bool CanConvert(Type objectType){return objectType == typeof(ContentType);}public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer){return new ContentType((string)reader.Value);}public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer){writer.WriteValue(((ContentType)value).ToString());} }轉換器注冊(WebApiConfig.cs):
?
public static void Register(HttpConfiguration config) {...config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new ContentTypeJsonConverter()); }控制器:
?
public class TestController : ApiController {public IHttpActionResult Post(FileData data){return this.Ok(data);} }請求:
?
POST /api/test HTTP/1.1 Content-Type: application/json Host: localhost:48278 Content-Length: 36{"contentType": "image/png" }響應:
?
HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?ZDpcd29ya1xUb0REXGFwaVx0ZXN0?= X-Powered-By: ASP.NET Date: Mon, 25 Jul 2016 07:06:02 GMT Content-Length: 27{"contentType":"image/png"}????本文轉自網絡文章,轉載此文章僅為分享知識,如有侵權,請聯系博主進行刪除。
總結
以上是生活随笔為你收集整理的【转】C# WebAPI中为自定义模型设置JSonConverter的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 丰田中国秀新技术:电动车接替家庭“电网”
- 下一篇: 日本70岁老奶奶坚持拼高达 对抗疾病带来