我正在寻找一种介绍除二进制格式化程序之外的内容到我的应用程序中,最终与Redis一起使用。我想要使用ServiceStack JSON,但它是否可以在接口方面满足我的需求?它可以序列化(通过插入自定义__type属性)
public IAsset Content;
但不包括
public List<IAsset> Contents;
- 在序列化数据中,列表为空。有没有办法序列化接口类型的列表?
该应用程序庞大且历史悠久,它使用的对象形状可能不会被允许更改。
我正在寻找一种介绍除二进制格式化程序之外的内容到我的应用程序中,最终与Redis一起使用。我想要使用ServiceStack JSON,但它是否可以在接口方面满足我的需求?它可以序列化(通过插入自定义__type属性)
public IAsset Content;
但不包括
public List<IAsset> Contents;
- 在序列化数据中,列表为空。有没有办法序列化接口类型的列表?
该应用程序庞大且历史悠久,它使用的对象形状可能不会被允许更改。
引用自http://www.servicestack.net/docs/framework/release-notes
你可能不需要做太多事情 :)
JSON和JSV文本序列化程序现在支持序列化和反序列化带有接口/抽象或对象类型的DTO。除其他外,这使您可以拥有一个IInterface属性,当序列化时,将在__type属性字段中包含其具体类型信息(类似于其他JSON序列化程序),当序列化时,填充该具体类型的实例(如果存在)。
[...]
注意:此功能会自动添加到所有抽象/接口/对象类型中,即您无需包含任何[KnownType]属性即可利用它。
不需要做太多:
public interface IAsset
{
string Bling { get; set; }
}
public class AAsset : IAsset
{
public string Bling { get; set; }
public override string ToString()
{
return "A" + Bling;
}
}
public class BAsset : IAsset
{
public string Bling { get; set; }
public override string ToString()
{
return "B" + Bling;
}
}
public class AssetBag
{
[JsonProperty(TypeNameHandling = TypeNameHandling.None)]
public List<IAsset> Assets { get; set; }
}
class Program
{
static void Main(string[] args)
{
try
{
var bag = new AssetBag
{
Assets = new List<IAsset> {new AAsset {Bling = "Oho"}, new BAsset() {Bling = "Aha"}}
};
string json = JsonConvert.SerializeObject(bag, new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Auto
});
var anotherBag = JsonConvert.DeserializeObject<AssetBag>(json, new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Auto
});