在ASP中无法将json反序列化为抽象类.净MVC
本文关键字:反序列化 抽象类 MVC json ASP | 更新日期: 2023-09-27 18:02:02
我知道关于这个问题有很多问题和答案,但是没有一个对我有帮助。
我有两个继承自一个抽象基类的类。我试图在我的控制器中编写POST方法,获得基类作为参数,但我得到异常:
MissingMethodException: Cannot create an abstract class.
我在这个答案中找到了解决方案:在Asp中反序列化Json到派生类型。. Net Web API,但是没有帮助。
我喜欢这个想法,并按照答案一直到最后,但仍然得到了相同的异常,我的代码从未被调用过。
为了隔离这个问题,我已经启动了新的ASP。. NET项目(SPA模板)并检查了我在清洁项目上的问题。我的实现:
我的JsonConverter实现与答案的一个形式相同:
public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>
/// this is very important, otherwise serialization breaks!
/// </summary>
public override bool CanWrite => false;
/// <summary>
/// Create an instance of objectType, based properties in the JSON object
/// </summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">contents of JSON object that will be
/// deserialized</param>
/// <returns></returns>
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
//////////////////////////////////////////
// This function never get called!!!!!!!!!
//////////////////////////////////////////
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
serializer.Populate(jObject.CreateReader(), target);
return target;
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
我的基类及其实现是:
[JsonConverter(typeof(MyCustomConverter))]
public abstract class BaseClass
{
private class MyCustomConverter : JsonCreationConverter<BaseClass>
{
protected override BaseClass Create(Type objectType,
Newtonsoft.Json.Linq.JObject jObject)
{
//////////////////////////////////////////
// No matter what I put in here.
// This function never get called!!!!!!!!!
//////////////////////////////////////////
return new Sub1()
{
Name = "aaaa",
Prop1 = 233
};
}
}
public int Prop1 { get; set; }
}
public class Sub1 : BaseClass
{
public string Name { get; set; }
}
我的控制器Post和Get方法是:
// GET: /Account/GetTest
[HttpGet]
public JsonResult GetTest()
{
// This function works as expected.
Sub1 sub1 = new Sub1
{
Name = "SomeName",
Prop1 = 5
};
return Json(sub1, JsonRequestBehavior.AllowGet);
}
// Post: /Account/PostTest
[HttpPost]
public JsonResult PostTest(BaseClass res)
{
// I never get to this point.
return Json(res, JsonRequestBehavior.AllowGet);
}
和我的JS测试代码,试图使用这个api是:
$.ajax({
url: '/Account/GetTest',
method: 'get',
cache: false,
success: function(data) {
// data arrive fine to this point
$.ajax({
url: '/Account/PostTest',
method: 'post',
cache: false,
data: data,
// I've also tried: data: JSON.stringify(data),
success: function () {
// I never get success...
alert('Success');
},
error: function () {
alert('Error Post');
}
});
},
error: function() {
alert('Error Get');
}
});
我也试着玩ajax参数,但没有任何运气。
有人知道我做错了什么吗?经过多次实验,我发现在基类上使用JsonConverter属性仅在ApiController中工作,而不是在常规MVC Controller中。我刚刚创建了新的ApiController,效果非常好。
另外,当发布json时,它应该包含contentType信息,所以它应该看起来像:$.ajax({
url: '/Account/PostTest',
method: 'post',
cache: false,
//////// NOTE THE NEXT 2 ATTRIBUTES
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
/////////////////
success: function () {
// I never get success...
alert('Success');
},
error: function () {
alert('Error Post');
}
});
using (WebClient client = new WebClient())
{
response = Newtonsoft.Json.Linq.JObject.Parse(client.DownloadString(fullUrl));
}
Newtonsoft.Json.Linq.JArray items = response.items;
Newtonsoft.Json.Linq.JArray selectedItems = new JArray();
foreach (dynamic rev in reviews)
{
if (rev.propertyWanted == "condition")
{
selectedReviews.Add(rev);
}
else
{
continue;
}
}
return selectedReviews;