【问题标题】:How to pass json data to abstract class?如何将json数据传递给抽象类?
【发布时间】:2017-03-16 14:38:22
【问题描述】:
public abstract class AbstractSearch
{
    public string Property { get; set; }
    public string TargetTypeName { get; set; }
}

public class DateSearch : AbstractSearch
{
    public DateTime? SearchTerm { get; set; }
    public DateComparators Comparator { get; set; }
}

public enum DateComparators
{
    Less,
    LessOrEqual,
    Equal,
    GreaterOrEqual,
    Greater,
    InRange
}

public class SearchViewModel
{
    public IEnumerable<AbstractSearch> SearchCriteria { get; set; }
}

如何将上述属性从客户端 JSON 传递给 SearchViewModel 类。

我需要通过 Json 将 JavaScript 中的 Property、TargetTypeName、SearchTerm、Comparator 传递给 webapi。

我正在使用 Web api 2.0 作为服务器端。是否可以将 Json 参数传递给 Inherited 类?

【问题讨论】:

  • 为什么不public IEnumerable&lt;DateSearch&gt; SearchCriteria { get; set; }
  • 没有 SearchViewModel 类是否可行?
  • @tym32167 我假设 OP 有其他继承自抽象的类,因此需要引用抽象而不是具体实现

标签: c# json


【解决方案1】:

如果您在客户端序列化时指定具体类型,您可以使用TypeNameHandling 来完成这项工作。您可以使用 JSON 中的 $type 属性指定类型。

模型绑定器将无法实例化抽象类。

配置 JSON.NET:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

然后以这种格式发布您的 JSON:

{
    "$type": "Namespace.DateSearch, AssemblyName"
    "Property": "..."
    "etc": ""
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 2014-11-28
  • 2021-05-08
  • 2011-05-21
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
相关资源
最近更新 更多