未能将json反序列化为ASP.Net MVC中的抽象类

时间:2016-08-11 13:19:20

标签: c# asp.net json asp.net-mvc asp.net-mvc-4

我知道这个问题有很多问题和答案,但没有人帮助过我。

我有两个继承自一个抽象基类的类。我试图在我的控制器中编写POST方法,将基类作为参数,但我得到了例外:

  

MissingMethodException:无法创建抽象类。

我在这个答案中找到了解决方案:Deserialising Json to derived types in Asp.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);
    }

我尝试使用此API的JS测试代码是:

$.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参数,但没有运气。

有人知道我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

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;