- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试序列化和反序列化 Node 对象树。我的抽象“节点”类以及从它派生的其他抽象类和具体类都在我的“Informa”项目中定义。此外,我在 Informa 中创建了一个用于序列化/反序列化的静态类。
首先,我将我的树解构为 Dictionary(guid,Node) 类型的平面列表,其中 guid 是节点的唯一 ID。
我能够毫无问题地序列化我的所有节点。但是当我尝试反序列化时,出现以下异常。
Error in line 1 position 227. Element 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value' contains data of the 'Informa:Building' data contract. The deserializer has no knowlege of any type that maps to this contract. Add the type corresponding to 'Building' to the list of known types - for example, by usying the KnownTypeAttribute or by adding it to the list of known types passed to DataContract Serializer.
所有派生自 Node 的类,包括 Building,都应用了 [KnownType(typeof(type t))] 属性。
我的序列化和反序列化方法如下:
public static void SerializeProject(Project project, string filePath)
{
try
{
Dictionary<Guid, Node> nodeDic = DeconstructProject(project);
Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
//serialize
DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary<Guid, Node>),"InformaProject","Informa");
ser.WriteObject(stream,nodeDic);
// Cleanup
stream.Close();
}
catch (Exception e)
{
MessageBox.Show("There was a problem serializing " + Path.GetFileName(filePath) + ". \n\nException:" + e.Message, "Doh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw e;
}
}
public static Project DeSerializeProject(string filePath)
{
try
{
Project proj;
// Read the file back into a stream
Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary<Guid, Node>), "InformaProject", "Informa");
Dictionary<Guid, Node> nodeDic = (Dictionary<Guid, Node>)ser.ReadObject(stream);
proj = ReconstructProject(nodeDic);
// Cleanup
stream.Close();
return proj;
}
catch (Exception e)
{
MessageBox.Show("There was a problem deserializing " + Path.GetFileName(filePath) + ". \n\nException:" + e.Message, "Doh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
最佳答案
All classes that derive from Node, including Building, have the [KnownType(typeof(type t))] attribute applied to them.
KnownType
通常应用于 base 类型 - 即
[DataContract, KnownType(typeof(Building)), ...]
abstract class Node { ... }
(注意 - 您还可以在 DataContractSerializer
构造函数中指定已知类型,不需要属性)
编辑您的回复
如果框架类不知道所有派生类型,那么您需要在创建序列化程序时指定已知类型:
[DataContract] abstract class SomeBase { }
[DataContract] class Foo : SomeBase { }
[DataContract] class Bar : SomeBase { }
...
// here the knownTypes argument is important
new DataContractSerializer(typeof(SomeBase),
new Type[] { typeof(Foo), typeof(Bar) });
这可以与(例如)preserveObjectReferences
等结合使用,方法是替换上一个示例中的 null
。
结束编辑
但是,如果没有可重现的东西(即 Node
和 Building
),将很难提供太多帮助。
另一个奇怪的事情;树结构非常适合DataContractSerializer
之类的东西——通常不需要先将它们展平,因为树可以简单地用 xml 表示。你真的需要把它弄平吗?
例子:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
[DataContract, KnownType(typeof(Building))]
abstract class Node {
[DataMember]
public int Foo {get;set;}
}
[DataContract]
class Building : Node {
[DataMember]
public string Bar {get;set;}
}
static class Program
{
static void Main()
{
Dictionary<Guid, Node> data = new Dictionary<Guid, Node>();
Type type = typeof(Dictionary<Guid, Node>);
data.Add(Guid.NewGuid(), new Building { Foo = 1, Bar = "a" });
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw))
{
DataContractSerializer dcs = new DataContractSerializer(type);
dcs.WriteObject(xw, data);
}
string xml = sw.ToString();
StringReader sr = new StringReader(xml);
using (XmlReader xr = XmlReader.Create(sr))
{
DataContractSerializer dcs = new DataContractSerializer(type);
Dictionary<Guid, Node> clone = (Dictionary<Guid, Node>)
dcs.ReadObject(xr);
foreach (KeyValuePair<Guid, Node> pair in clone)
{
Console.WriteLine(pair.Key + ": " + pair.Value.Foo + "/" +
((Building)pair.Value).Bar);
}
}
}
}
关于c# - 反序列化器不知道映射到该契约的任何类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/736900/
我正在尝试构建某种形式的动态 Corda 合约,该合约具有一个可以保存独立合约列表和这些合约的独立状态的状态。 为了揭开这个概念的神秘面纱,请将“动态 Corda 合约”视为一个抽象类,它具有 Lis
怀念Collections.unmodifiableMap(),我一直在实现基于this discussion 的只读IDictionary 包装器,我的单元测试很快就遇到了问题: Assert.Ar
在消费者测试结束时我需要执行两个步骤: 完成模拟服务器 将协议(protocol)发布给经纪人。 一开始我是先发布再定稿,像这样: var opts = { //broker info } pac
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 3 年前。 Improve
您好, WCF 中数据/服务契约(Contract)的默认命名空间是 "http://tempuri.org/" .通过设置 ServiceContract.Namespace和 ServiceBeh
Using Attachments页面状态: Attachments are ZIP/JAR files referenced from a transaction by hash, but not
说我有一个方法 public void PrintStuff(string stuff, Color color, PageDimensions dimensions) { Assert.I
Mortgage.new({ from: ownerAccount, gas: defaultGas }).then( function(loanInstance) { loa
有很多问题询问是否混合异步和同步代码。 大多数答案都说为异步方法公开同步包装器和为同步方法公开异步包装器是个坏主意。 但是,没有一个答案解决您必须混合使用异步和同步代码的特定场景,以及如何避免由此产生
我是来自 PHP/Larvel、Ruby/Rails 和 Python/Django 的 Spring 新手。来自这些框架,我习惯于只看到模型(Entity/Dao?),其他一切都由 Framewor
我正在尝试为一些广泛使用的接口(interface)编写契约(Contract)测试: 沿着: public abstract class MyInterfaceContractTest extend
这是来自自定义 Microsoft .NET 运行时实现的代码,我有以下问题: public static string ToBase64String(byte[] inArray, int
我正在用遗留代码重构一个巨大的 C 库,其中许多函数在参数列表上都有指针。我还为新创建的函数编写单元测试以确保我没有破坏任何东西(除了来自单元测试的所有好东西,这是我的主要动机)。我也不允许更改库的
我的类有一个内部属性返回 List ,并且我想使用静态检查来帮助我不在我的程序集中做任何愚蠢的事情,并可能向该集合添加 null。 我在 foreach 的循环变量上收到这个静态警告在属性(prope
我在这个问题上花了几个小时...这是我的代码: public static IEnumerable Generate(this Func generator) where T : class {
我有兴趣了解更多关于contract-first 网络服务的信息,包括如何将它们组合在一起。 谁能推荐有用的资源来解释所需的方面/组件以及如何生成它们? 除了 Spring 的契约优先 Web 服务之
我刚刚将我的联系方式、银行和税务详细信息上传到 iTunes Connect;这个处理通常需要多长时间?我只能找到 5 年以上的信息。 最佳答案 契约(Contract)审核过程大约需要 20 分钟。
假设我们有一个类 Student使用以下构造函数: /** Initializes a student instance. * @param matrNr matriculation numb
使用 CXF 创建契约(Contract)最后的 Web 服务似乎是快速创建基于 SOAP 或 REST 的 Web 服务的有效方式。但是,我不清楚/不确定以下内容,非常感谢您提供见解/反馈: con
引自 Effective Java - Second Edition by Joshua Bloch For floating-point fields, use Double.compare or
我是一名优秀的程序员,十分优秀!