Ron*_*ton 11 .net rest webforms json.net asp.net-web-api
所以这是我的情况.我正在WebForms应用程序中实现一个WEB API.我有一堆动态类,它们本质上是字典,需要使用自定义JSON序列化格式化程序才能正常工作(因为默认转换器只显示一堆键值配对).
所以首先我创建了一个自定义JSON转换器:
/// <summary>
/// A class to convert entities to JSON
/// </summary>
public class EntityJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsSubclassOf(typeof(Entity));
}
public override bool CanRead
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Details not important. This code is called and works perfectly.
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Details not important. This code is *never* called for some reason.
}
}
Run Code Online (Sandbox Code Playgroud)
一旦我定义了I,然后将其插入到全局JSON媒体类型格式化器中:
// Add a custom converter for Entities.
foreach (var formatter in GlobalConfiguration.Configuration.Formatters)
{
var jsonFormatter = formatter as JsonMediaTypeFormatter;
if (jsonFormatter == null)
continue;
jsonFormatter.SerializerSettings.Converters.Add(new EntityJsonConverter());
}
Run Code Online (Sandbox Code Playgroud)
最后,我的测试API(将来会有更多的添加,我只是试图测试系统,"联系人"继承自"实体"):
public class ContactController : ApiController
{
public IEnumerable<Contact> Get()
{
// Details not important. Works perfectly.
}
[HttpPost]
public bool Update(Contact contact)
{
// Details not important. Contact is always "null".
}
}
Run Code Online (Sandbox Code Playgroud)
所以这是我在调试时看到的内容:
网站呼叫"获取":
网站呼叫"更新":
我完全感到困惑.我不明白为什么这在序列化时有效,但整个过程似乎只是在尝试反序列化时跳过我的自定义转换器.任何人都有任何想法,我做错了什么?
谢谢!
| 归档时间: |
|
| 查看次数: |
6707 次 |
| 最近记录: |