我设置了一个WebApi控制器,它应该返回一组不同类型的对象。请仔细看看我的虚拟代码:
interface IDish
{
int ID { get; set; }
string Name { get; set; }
}
class Steak : IDish
{
public int ID { get; set; }
public string Name { get; set; }
public string CookingStyle { get; set; }
public int Weight { get; set; }
}
class Soup : IDish
{
public int ID { get; set; }
public string Name { get; set; }
}
class Dessert : IDish
{
public int ID { get; set; }
public string Name { get; set; }
public bool ContainsSugar { get; set; }
}
public class DishController : ApiController
{
public IEnumerable<IDish> Get()
{
var dishes = busisnessLogic.GetDishes();
return dishes;
}
}
正如您所看到的,在控制器中,我正在从业务逻辑中检索一系列ID。请不要过分关注具体课程。它们只是让这里的事情更容易解释的样本。真正的商业背景完全不同。
那么,我的问题是什么?当API控制器返回IDishes(在我的例子中为Json)时,只有IDish接口的公共属性被写入Json输出。
相反,我希望将具体类的所有公共属性写入Json输出。所以,例如,如果一个IDish是“牛排”,我想写出它的ID,姓名,CookingStyle和Weight。因此,只有ID和名称,如果它是“汤”,ID,名称和ContainsSugar,如果它是“甜点”。
有没有简单的方法来实现这一目标?有时我往往不会在树林前看到树木......; - )
谢谢你们!
答案 0 :(得分:1)
我需要几乎相同的功能,我认为有两种方法可以:
var jsonFormatter = config.Formatters.JsonFormatter;
var jsonSerializerSettings = new JsonSerializerSettings();
jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
说明: https://github.com/ayoung/Newtonsoft.Json/blob/master/Newtonsoft.Json/TypeNameHandling.cs
基本上,您需要做的是: - 创建一个派生自JsonCreationConverter的类,在该类中重写Create方法以手动选择要创建的对象的类型 - 您更新设置:
var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.Converters.Add(new YourCustomJsonConverter());
jsonFormatter.SerializerSettings = jsonSerializerSettings;
查看这篇文章,它逐步描述: http://dotnetbyexample.blogspot.co.uk/2012/02/json-deserialization-with-jsonnet-class.html